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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4,854,446 | Save Accents in MySQL Database | <p><br/> I'm trying to save French accents in my database, but they aren't saved like they should in the DB.<br/>For example, a "é" is saved as "é".<br/>I've tried to set my files to "Unicode (utf-8)", the fields in the DB are "utf8_general_ci" as well as the DB itself.<br/>When I look at my data posted through AJAX with Firebug, I see the accent passed as "é", so it's correct.<br/><br/>Thanks and let me know you need more info!</p> | 8,780,302 | 9 | 0 | null | 2011-01-31 18:13:58.63 UTC | 9 | 2022-09-13 19:02:36.917 UTC | 2014-04-14 02:01:25.317 UTC | null | 857,004 | null | 585,106 | null | 1 | 27 | php|mysql|character-encoding|diacritics | 45,567 | <p>Personally I solved the same issue by adding after the <strong>MySQL connection code</strong>:</p>
<pre><code>mysql_set_charset("utf8");
</code></pre>
<p>or for mysqli:</p>
<pre><code>mysqli_set_charset($conn, "utf8");
</code></pre>
<p>or the mysqli OOP equivalent:</p>
<pre><code>$conn->set_charset("utf8");
</code></pre>
<p>And sometimes you'll have to define the <strong>main php charset</strong> by adding this code:</p>
<pre><code>mb_internal_encoding('UTF-8');
</code></pre>
<p>On the client HTML side you have to add the following header data :</p>
<pre><code><meta http-equiv="Content-type" content="text/html;charset=utf-8" />
</code></pre>
<p>In order to use JSON AJAX results (e.g. by using jQuery), you should define the header by adding :</p>
<pre><code>header("Content-type: application/json;charset=utf8");
json_encode(
some_data
);
</code></pre>
<p>This should do the trick</p> |
5,404,856 | How to disable touch input to all views except the top-most view? | <p>I have a view with multiple subviews. When a user taps a subview, the subview expands in size to cover most of the screen, but some of the other subviews are still visible underneath.</p>
<p>I want my app to ignore touches on the other subviews when one of the subviews is "expanded" like this. Is there a simple way to achieve this? I can write code to handle this, but I was hoping there's a simpler built-in way.</p> | 5,404,950 | 12 | 0 | null | 2011-03-23 11:56:56 UTC | 16 | 2021-08-16 15:42:57.507 UTC | 2013-08-07 11:17:38.547 UTC | null | 640,731 | null | 14,606 | null | 1 | 47 | iphone|ios|cocoa-touch|uiview|user-interaction | 84,967 | <p>Hope this help...</p>
<pre><code>[[yourSuperView subviews]
makeObjectsPerformSelector:@selector(setUserInteractionEnabled:)
withObject:[NSNumber numberWithBool:FALSE]];
</code></pre>
<p>which will disable userInteraction of a view's immediate subviews..Then give userInteraction to the only view you wanted</p>
<pre><code>yourTouchableView.setUserInteraction = TRUE;
</code></pre>
<h2>EDIT:</h2>
<p>It seems in iOS disabling userInteraction on a parent view doesn't disable userInteraction on its childs.. <strong>So the code above (I mean the one with</strong> <code>makeObjectsPerformSelector:</code>)<strong>will only work to disable userInteraction of a parent's immediate subviews..</strong> </p>
<p>See user madewulf's answer which recursively get all subviews and disable user interaction of all of them. Or if you need to disable userInteraction of this view in many places in the project, You can categorize UIView to add that feature.. Something like this will do..</p>
<pre><code>@interface UIView (UserInteractionFeatures)
-(void)setRecursiveUserInteraction:(BOOL)value;
@end
@implementation UIView(UserInteractionFeatures)
-(void)setRecursiveUserInteraction:(BOOL)value{
self.userInteractionEnabled = value;
for (UIView *view in [self subviews]) {
[view setRecursiveUserInteraction:value];
}
}
@end
</code></pre>
<p>Now you can call</p>
<pre><code>[yourSuperView setRecursiveUserInteraction:NO];
</code></pre>
<p>Also user @lxt's suggestion of adding an invisible view on top of all view's is one other way of doing it..</p> |
5,553,352 | How do I check if file exists in Makefile so I can delete it? | <p>In the clean section of my <code>Makefile</code> I am trying to check if the file exists before deleting permanently. I use this code but I receive errors.</p>
<p>What's wrong with it?</p>
<pre class="lang-sh prettyprint-override"><code> if [ -a myApp ]
then
rm myApp
fi
</code></pre>
<p>I get this error message</p>
<pre class="lang-sh prettyprint-override"><code> if [ -a myApp ]
/bin/sh: Syntax error: end of file unexpected (expecting "then")
make: *** [clean] Error 2
</code></pre> | 47,828,799 | 16 | 4 | null | 2011-04-05 14:17:35.547 UTC | 29 | 2022-06-04 02:12:05.44 UTC | 2022-03-29 07:25:32.903 UTC | null | 2,226,755 | null | 245,416 | null | 1 | 175 | makefile | 256,735 | <p>The second top answer mentions <code>ifeq</code>, however, it fails to mention that this <code>ifeq</code> must be at the same indentation level in the makefile as the name of the target, e.g., to download a file only if it doesn't currently exist, the following code could be used:</p>
<pre class="lang-Makefile prettyprint-override"><code>download:
ifeq (,$(wildcard ./glob.c))
curl … -o glob.c
endif
# THIS DOES NOT WORK!
download:
ifeq (,$(wildcard ./glob.c))
curl … -o glob.c
endif
</code></pre> |
5,548,893 | jQuery DataTables: Delay search until 3 characters been typed OR a button clicked | <p>Is there please an option to start the search only after 3 characters have been typed in?</p>
<p>I have written a PHP-script for colleagues displaying 20,000 entries and they complain, that when typing a word, the first few letters cause everything to freeze.</p>
<p>An alternative would be to have the search to be started by a button clicked and not by character typing.</p>
<p>Below is my current code:</p>
<pre><code>$("#my_table").dataTable( {
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bAutoWidth": false,
"aoColumns": [
/* qdatetime */ { "bSearchable": false },
/* id */ null,
/* name */ null,
/* category */ null,
/* appsversion */ null,
/* osversion */ null,
/* details */ { "bVisible": false },
/* devinfo */ { "bVisible": false, "bSortable": false }
],
"oLanguage": {
"sProcessing": "Wait please...",
"sZeroRecords": "No ids found.",
"sInfo": "Ids from _START_ to _END_ of _TOTAL_ total",
"sInfoEmpty": "Ids from 0 to 0 of 0 total",
"sInfoFiltered": "(filtered from _MAX_ total)",
"sInfoPostFix": "",
"sSearch": "Search:",
"sUrl": "",
"oPaginate": {
"sFirst": "&lt;&lt;",
"sLast": "&gt;&gt;",
"sNext": "&gt;",
"sPrevious": "&lt;"
},
"sLengthMenu": 'Display <select>' +
'<option value="10">10</option>' +
'<option value="20">20</option>' +
'<option value="50">50</option>' +
'<option value="100">100</option>' +
'<option value="-1">all</option>' +
'</select> ids'
}
} );
</code></pre> | 23,897,722 | 24 | 1 | null | 2011-04-05 07:59:48.887 UTC | 33 | 2022-08-08 00:32:17.713 UTC | 2017-11-16 08:00:45.69 UTC | null | 165,071 | null | 165,071 | null | 1 | 88 | jquery|datatables | 85,794 | <p>Solution for version 1.10 -</p>
<p>After looking here for a complete answer and not finding one, I've written this (utilizing code from the documentation, and a few answers here).</p>
<p>The below code works to delay searching until at least 3 characters are entered:</p>
<pre><code>// Call datatables, and return the API to the variable for use in our code
// Binds datatables to all elements with a class of datatable
var dtable = $(".datatable").dataTable().api();
// Grab the datatables input box and alter how it is bound to events
$(".dataTables_filter input")
.unbind() // Unbind previous default bindings
.bind("input", function(e) { // Bind our desired behavior
// If the length is 3 or more characters, or the user pressed ENTER, search
if(this.value.length >= 3 || e.keyCode == 13) {
// Call the API search function
dtable.search(this.value).draw();
}
// Ensure we clear the search if they backspace far enough
if(this.value == "") {
dtable.search("").draw();
}
return;
});
</code></pre> |
16,934,663 | Displaying images from MySQL database in JSF datatable | <p>I have MySQL database which stores images in a <code>blob</code> column. I would like to show them in a PrimeFaces <code><p:dataTable></code>. How can I achieve this?</p> | 16,940,909 | 2 | 4 | null | 2013-06-05 08:08:20.397 UTC | 8 | 2015-07-18 08:24:28.023 UTC | 2013-07-13 13:08:57.337 UTC | null | 157,882 | null | 2,436,180 | null | 1 | 4 | mysql|image|jsf|primefaces|datatable | 13,932 | <p>You can use <a href="http://www.primefaces.org/showcase/ui/dynamicImage.jsf" rel="nofollow noreferrer"><code><p:graphicImage></code></a> to display images stored in a <code>byte[]</code>, regardless of the <code>byte[]</code> source (DB, disk file system, network, etc). Simplest example is:</p>
<pre class="lang-html prettyprint-override"><code><p:graphicImage value="#{bean.streamedContent}" />
</code></pre>
<p>which refers a <code>StreamedContent</code> property.</p>
<p>This has however a pitfall, particularly when used in an iterating component such as a data table: the getter method will be invoked twice; the first time by JSF itself to generate the URL for <code><img src></code> and the second time by webbrowser when it needs to download the image content based on the URL in <code><img src></code>. To be efficient, you should not be hitting the DB in the first getter call. Also, to parameterize the getter method call so that you can use a generic method wherein you pass a specific image ID, you should be using a <code><f:param></code> (please note that EL 2.2 feature of passing method arguments won't work at all as this doesn't end up in URL of <code><img src></code>!).</p>
<p>Summarized, this should do:</p>
<pre class="lang-html prettyprint-override"><code><p:dataTable value="#{bean.items}" var="item">
<p:column>
<p:graphicImage value="#{imageStreamer.image}">
<f:param name="id" value="#{item.imageId}" />
</p:graphicImage>
</p:column>
</p:dataTable>
</code></pre>
<p>The <code>#{item.imageId}</code> obviously returns the unique idenfitier of the image in the DB (the primary key) and thus <em>not</em> the <code>byte[]</code> content. The <code>#{imageStreamer}</code> is an application scoped bean which look like this:</p>
<pre class="lang-java prettyprint-override"><code>@ManagedBean
@ApplicationScoped
public class ImageStreamer {
@EJB
private ImageService service;
public StreamedContent getImage() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
// So, we're rendering the HTML. Return a stub StreamedContent so that it will generate right URL.
return new DefaultStreamedContent();
} else {
// So, browser is requesting the image. Return a real StreamedContent with the image bytes.
String imageId = context.getExternalContext().getRequestParameterMap().get("imageId");
Image image = imageService.find(Long.valueOf(imageId));
return new DefaultStreamedContent(new ByteArrayInputStream(image.getBytes()));
}
}
}
</code></pre>
<p>The <code>Image</code> class is in this particular example just an <code>@Entity</code> with a <code>@Lob</code> on <code>bytes</code> property (as you're using JSF, I of cource assume that you're using JPA to interact with the DB).</p>
<pre class="lang-java prettyprint-override"><code>@Entity
public class Image {
@Id
@GeneratedValue(strategy = IDENTITY) // Depending on your DB, of course.
private Long id;
@Lob
private byte[] bytes;
// ...
}
</code></pre>
<p>The <code>ImageService</code> is just a standard <code>@Stateless</code> EJB, nothing special to see here:</p>
<pre class="lang-java prettyprint-override"><code>@Stateless
public class ImageService {
@PersistenceContext
private EntityManager em;
public Image find(Long id) {
return em.find(Image.class, id);
}
}
</code></pre>
<h3>See also:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/8207325/display-image-from-database-with-pgraphicimage/">Display dynamic image from database with p:graphicImage and StreamedContent</a></li>
</ul> |
12,249,136 | ReferenceError: google is not defined | <p>I use google map's api in my website to show couple of locations. Google Maps is working just fine in my local solution but not in my website. I changed this source</p>
<pre><code><script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.5&sensor=false"> </script>
</code></pre>
<p>to this one. and i again changed this </p>
<pre><code><script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
</code></pre>
<p>with this one... </p>
<pre><code><script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"> </script>
</code></pre>
<p>Only thing it says: <strong>ReferenceError: google is not defined</strong></p>
<p>Does anyone familiar with such problem?</p> | 12,284,981 | 4 | 0 | null | 2012-09-03 13:47:54.923 UTC | 3 | 2021-07-05 14:13:02.13 UTC | 2012-09-04 12:27:16.623 UTC | null | 1,218,067 | null | 1,218,067 | null | 1 | 14 | google-maps | 106,790 | <p>Owing to the fact that my website uses <strong>https</strong> for the connection, I can not use <a href="http://maps.google.com/maps/api/js?sensor=false" rel="nofollow noreferrer">http://maps.google.com/maps/api/js?sensor=false</a>. When I debug the whole page, this link says: Warning : <strong>The page index.html ran insecure content</strong>. so I made another search on google and came across to this <a href="https://stackoverflow.com/questions/7309013/warning-the-page-index-html-ran-insecure-content">question</a>. so what basically causes a problem is not using https link in the source part so the correct link will be (for me)</p>
<pre><code>https://maps.google.com/maps/api/js?sensor=false
</code></pre>
<p>now everything works just fine!</p> |
12,504,954 | How to start an Intent from a ResolveInfo | <p>I'm trying to make a custom launcher for android, and I'm trying to figure out how to launch a different application form mine. I figured the way to do it was intents, and I've found a post on it here:</p>
<p><a href="https://stackoverflow.com/questions/2780102/open-another-application-from-your-own-intent">Open another application from your own (intent)</a></p>
<p>I don't really understand the answer though! Can someone give me a concise snippet or series of steps to go from a single ResolveInfo to launching the app represented by that ResolveInfo?</p> | 12,511,404 | 2 | 0 | null | 2012-09-20 01:20:26.767 UTC | 8 | 2013-06-02 23:08:00.327 UTC | 2017-05-23 12:02:26.147 UTC | null | -1 | null | 1,123,960 | null | 1 | 26 | android|android-intent|launcher | 13,315 | <p>Given a <code>ResolveInfo</code> named <code>launchable</code>:</p>
<pre><code>ActivityInfo activity=launchable.activityInfo;
ComponentName name=new ComponentName(activity.applicationInfo.packageName,
activity.name);
Intent i=new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_LAUNCHER);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
i.setComponent(name);
startActivity(i);
</code></pre>
<p>(from <a href="https://github.com/commonsguy/cw-omnibus/tree/master/Introspection/Launchalot">https://github.com/commonsguy/cw-omnibus/tree/master/Introspection/Launchalot</a>)</p> |
12,196,756 | Significance level added to matrix correlation heatmap using ggplot2 | <p>I wonder how one can add another layer of important and needed complexity to a matrix correlation heatmap like for example the p value after the manner of the significance level stars in addition to the R2 value (-1 to 1)?<br>
It was NOT INTENDED in this question to put significance level stars OR the p values as text on each square of the matrix BUT rather to show this in a graphical out-of-the-box representation of significance level on each square of the matrix. I think only those who enjoy the blessing of INNOVATIVE thinking can win the applause to unravel this kind of solution in order to have the best way to represent that added component of complexity to our "half-of-the-truth matrix correlation heatmaps". I googled a lot but never seen a proper or I shall say an "eye-friendly" way to represent the significance level PLUS the standard color shades that reflect the R coefficient.<br>
The reproducible data set is found here:<br>
<a href="http://learnr.wordpress.com/2010/01/26/ggplot2-quick-heatmap-plotting/" rel="noreferrer">http://learnr.wordpress.com/2010/01/26/ggplot2-quick-heatmap-plotting/</a><br>
The R code please find below:</p>
<pre><code>library(ggplot2)
library(plyr) # might be not needed here anyway it is a must-have package I think in R
library(reshape2) # to "melt" your dataset
library (scales) # it has a "rescale" function which is needed in heatmaps
library(RColorBrewer) # for convenience of heatmap colors, it reflects your mood sometimes
nba <- read.csv("http://datasets.flowingdata.com/ppg2008.csv")
nba <- as.data.frame(cor(nba[2:ncol(nba)])) # convert the matrix correlations to a dataframe
nba.m <- data.frame(row=rownames(nba),nba) # create a column called "row"
rownames(nba) <- NULL #get rid of row names
nba <- melt(nba)
nba.m$value<-cut(nba.m$value,breaks=c(-1,-0.75,-0.5,-0.25,0,0.25,0.5,0.75,1),include.lowest=TRUE,label=c("(-0.75,-1)","(-0.5,-0.75)","(-0.25,-0.5)","(0,-0.25)","(0,0.25)","(0.25,0.5)","(0.5,0.75)","(0.75,1)")) # this can be customized to put the correlations in categories using the "cut" function with appropriate labels to show them in the legend, this column now would be discrete and not continuous
nba.m$row <- factor(nba.m$row, levels=rev(unique(as.character(nba.m$variable)))) # reorder the "row" column which would be used as the x axis in the plot after converting it to a factor and ordered now
#now plotting
ggplot(nba.m, aes(row, variable)) +
geom_tile(aes(fill=value),colour="black") +
scale_fill_brewer(palette = "RdYlGn",name="Correlation") # here comes the RColorBrewer package, now if you ask me why did you choose this palette colour I would say look at your battery charge indicator of your mobile for example your shaver, won't be red when gets low? and back to green when charged? This was the inspiration to choose this colour set.
</code></pre>
<p>The matrix correlation heatmap should look like this:<br>
<img src="https://i.stack.imgur.com/EQ6Oy.png" alt="enter image description here"></p>
<p>Hints and ideas to enhance the solution:<br>
- This code might be useful to have an idea about the significance level stars taken from this website:<br>
<a href="http://ohiodata.blogspot.de/2012/06/correlation-tables-in-r-flagged-with.html" rel="noreferrer">http://ohiodata.blogspot.de/2012/06/correlation-tables-in-r-flagged-with.html</a><br>
R code: </p>
<pre><code>mystars <- ifelse(p < .001, "***", ifelse(p < .01, "** ", ifelse(p < .05, "* ", " "))) # so 4 categories
</code></pre>
<p>- The significance level can be added as colour intensity to each square like alpha aesthetics but I don't think this will be easy to interpret and to capture<br>
- Another idea would be to have 4 different sizes of squares corresponding to the stars, of course giving the smallest to the non significant and increases to a full size square if highest stars<br>
- Another idea to include a circle inside those significant squares and the thickness of the line of the circle corresponds to the level of significance (the 3 remaining categories) all of them of one colour<br>
- Same as above but fixing the line thickness while giving 3 colours for the 3 remaining significant levels<br>
- May be you come up with better ideas, who knows?</p> | 12,226,215 | 3 | 5 | null | 2012-08-30 12:22:25.6 UTC | 20 | 2019-11-10 21:50:49.967 UTC | 2018-02-23 00:43:09.5 UTC | null | 8,270,343 | null | 1,288,722 | null | 1 | 30 | r|ggplot2|correlation|heatmap|significance | 21,988 | <p>This is just an attempt to enhance towards the final solution, I plotted the stars here as indicator of the solution, but as I said the aim is to find a graphical solution that can speak better than the stars. I just used geom_point and alpha to indicate significance level but the problem that the NAs (that includes the non-significant values as well) will show up like that of three stars level of significance, how to fix that? I think that using one colour might be more eye-friendly when using many colors and to avoid burdening the plot with many details for the eyes to resolve. Thanks in advance.<br>
Here is the plot of my first attempt:<br>
<img src="https://i.stack.imgur.com/aNEMK.png" alt="enter image description here"></p>
<p>or might be this better?!<br>
<img src="https://i.stack.imgur.com/HFUmd.png" alt="enter image description here"></p>
<p>I think the best till now is the one below, until you come up with something better !
<img src="https://i.stack.imgur.com/FdPXQ.png" alt="enter image description here"></p>
<p>As requested, the below code is for the last heatmap: </p>
<pre><code># Function to get the probability into a whole matrix not half, here is Spearman you can change it to Kendall or Pearson
cor.prob.all <- function (X, dfr = nrow(X) - 2) {
R <- cor(X, use="pairwise.complete.obs",method="spearman")
r2 <- R^2
Fstat <- r2 * dfr/(1 - r2)
R<- 1 - pf(Fstat, 1, dfr)
R[row(R) == col(R)] <- NA
R
}
# Change matrices to dataframes
nbar<- as.data.frame(cor(nba[2:ncol(nba)]),method="spearman") # to a dataframe for r^2
nbap<- as.data.frame(cor.prob.all(nba[2:ncol(nba)])) # to a dataframe for p values
# Reset rownames
nbar <- data.frame(row=rownames(nbar),nbar) # create a column called "row"
rownames(nbar) <- NULL
nbap <- data.frame(row=rownames(nbap),nbap) # create a column called "row"
rownames(nbap) <- NULL
# Melt
nbar.m <- melt(nbar)
nbap.m <- melt(nbap)
# Classify (you can classify differently for nbar and for nbap also)
nbar.m$value2<-cut(nbar.m$value,breaks=c(-1,-0.75,-0.5,-0.25,0,0.25,0.5,0.75,1),include.lowest=TRUE, label=c("(-0.75,-1)","(-0.5,-0.75)","(-0.25,-0.5)","(0,-0.25)","(0,0.25)","(0.25,0.5)","(0.5,0.75)","(0.75,1)")) # the label for the legend
nbap.m$value2<-cut(nbap.m$value,breaks=c(-Inf, 0.001, 0.01, 0.05),label=c("***", "** ", "* "))
nbar.m<-cbind.data.frame(nbar.m,nbap.m$value,nbap.m$value2) # adding the p value and its cut to the first dataset of R coefficients
names(nbar.m)[5]<-paste("valuep") # change the column names of the dataframe
names(nbar.m)[6]<-paste("signif.")
nbar.m$row <- factor(nbar.m$row, levels=rev(unique(as.character(nbar.m$variable)))) # reorder the variable factor
# Plotting the matrix correlation heatmap
# Set options for a blank panel
po.nopanel <-list(opts(panel.background=theme_blank(),panel.grid.minor=theme_blank(),panel.grid.major=theme_blank()))
pa<-ggplot(nbar.m, aes(row, variable)) +
geom_tile(aes(fill=value2),colour="white") +
scale_fill_brewer(palette = "RdYlGn",name="Correlation")+ # RColorBrewer package
opts(axis.text.x=theme_text(angle=-90))+
po.nopanel
pa # check the first plot
# Adding the significance level stars using geom_text
pp<- pa +
geom_text(aes(label=signif.),size=2,na.rm=TRUE) # you can play with the size
# Workaround for the alpha aesthetics if it is good to represent significance level, the same workaround can be applied for size aesthetics in ggplot2 as well. Applying the alpha aesthetics to show significance is a little bit problematic, because we want the alpha to be low while the p value is high, and vice verse which can't be done without a workaround
nbar.m$signif.<-rescale(as.numeric(nbar.m$signif.),to=c(0.1,0.9)) # I tried to use to=c(0.1,0.9) argument as you might expect, but to avoid problems with the next step of reciprocal values when dividing over one, this is needed for the alpha aesthetics as a workaround
nbar.m$signif.<-as.factor(0.09/nbar.m$signif.) # the alpha now behaves as wanted except for the NAs values stil show as if with three stars level, how to fix that?
# Adding the alpha aesthetics in geom_point in a shape of squares (you can improve here)
pp<- pa +
geom_point(data=nbar.m,aes(alpha=signif.),shape=22,size=5,colour="darkgreen",na.rm=TRUE,legend=FALSE) # you can remove this step, the result of this step is seen in one of the layers in the above green heatmap, the shape used is 22 which is again a square but the size you can play with it accordingly
</code></pre>
<p>I hope that this can be a step forward to reach there! Please note:<br>
- Some suggested to classify or cut the R^2 differently, ok we can do that of course but still we want to show the audience GRAPHICALLY the significance level instead of troubling the eye with the star levels. Can we ACHIEVE that in principle or not?<br>
- Some suggested to cut the p values differently, Ok this can be a choice after failure of showing the 3 levels of significance without troubling the eye. Then it might be better to show significant/non-significant without levels<br>
- There might be a better idea you come up with for the above workaround in ggplot2 for alpha and size aesthetics, hope to hear from you soon !<br>
- The question is not answered yet, waiting for an innovative solution !
- Interestingly, "corrplot" package does it! I came up with this graph below by this package, PS: the crossed squares are not significant ones, level of signif=0.05. But how can we translate this to ggplot2, can we?! </p>
<p><img src="https://i.stack.imgur.com/Pvrn7.png" alt="enter image description here"> </p>
<p>-Or you can do circles and hide those non-significant? how to do this in ggplot2?!<br>
<img src="https://i.stack.imgur.com/FIjog.png" alt="enter image description here"></p> |
12,412,324 | Python class returning value | <p>I'm trying to create a class that returns a value, not self.</p>
<p>I will show you an example comparing with a list:</p>
<pre><code>>>> l = list()
>>> print(l)
[]
>>> class MyClass:
>>> pass
>>> mc = MyClass()
>>> print mc
<__main__.MyClass instance at 0x02892508>
</code></pre>
<p>I need that MyClass returns a list, like <code>list()</code> does, not the instance info. I know that I can make a subclass of list. But is there a way to do it without subclassing?</p>
<p>I want to imitate a list (or other objects):</p>
<pre><code>>>> l1 = list()
>>> l2 = list()
>>> l1
[]
>>> l2
[]
>>> l1 == l2
True
>>> class MyClass():
def __repr__(self):
return '[]'
>>> m1 = MyClass()
>>> m2 = MyClass()
>>> m1
[]
>>> m2
[]
>>> m1 == m2
False
</code></pre>
<p>Why is <code>m1 == m2</code> False? This is the question.</p>
<p>I'm sorry if I don't respond to all of you. I'm trying all the solutions you give me. I cant use <code>def</code>, because I need to use functions like setitem, getitem, etc.</p> | 12,412,839 | 6 | 9 | null | 2012-09-13 18:14:08.44 UTC | 18 | 2021-02-18 17:28:23.78 UTC | 2015-05-12 19:01:40.883 UTC | null | 562,769 | null | 1,669,442 | null | 1 | 34 | python|class|return | 237,308 | <p>If what you want is a way to turn your class into kind of a list without subclassing <code>list</code>, then just make a method that returns a list:</p>
<pre><code>def MyClass():
def __init__(self):
self.value1 = 1
self.value2 = 2
def get_list(self):
return [self.value1, self.value2...]
>>>print MyClass().get_list()
[1, 2...]
</code></pre>
<p>If you meant that <code>print MyClass()</code> will print a list, just override <code>__repr__</code>:</p>
<pre><code>class MyClass():
def __init__(self):
self.value1 = 1
self.value2 = 2
def __repr__(self):
return repr([self.value1, self.value2])
</code></pre>
<p>EDIT:
I see you meant how to make objects <strong>compare</strong>. For that, you override the <code>__cmp__</code> method.</p>
<pre><code>class MyClass():
def __cmp__(self, other):
return cmp(self.get_list(), other.get_list())
</code></pre> |
12,162,657 | Possible to print more than 100 rows of a data.table? | <p>The data.table has a nice feature that suppresses output to the head and tail of the table.</p>
<p>Is it possible to view / print more than 100 rows at once?</p>
<pre><code>library(data.table)
## Convert the ubiquitous "iris" data to a data.table
dtIris = as.data.table(iris)
## Printing 100 rows is possible
dtIris[1:100, ]
## Printing 101 rows is truncated
dtIris[1:101, ]
</code></pre>
<p>I often have data.table results that are somewhat large (e.g. 200 rows) that I just want to view.</p> | 12,162,762 | 5 | 1 | null | 2012-08-28 15:31:50.347 UTC | 11 | 2022-07-17 20:37:17.753 UTC | 2022-07-17 20:37:17.753 UTC | null | 1,161,484 | null | 573,778 | null | 1 | 51 | r|printing|data.table|output-formatting | 48,168 | <p>The print method of <code>data.table</code> has an argument <code>nrows</code>:</p>
<pre><code>args(data.table:::print.data.table)
function (x, nrows = 100L, digits = NULL, ...)
</code></pre>
<p>You can use this to control how many rows get printed:</p>
<pre><code>print(dtIris, nrow=105)
.....
99: 5.1 2.5 3.0 1.1 versicolor
100: 5.7 2.8 4.1 1.3 versicolor
101: 6.3 3.3 6.0 2.5 virginica
102: 5.8 2.7 5.1 1.9 virginica
103: 7.1 3.0 5.9 2.1 virginica
104: 6.3 2.9 5.6 1.8 virginica
105: 6.5 3.0 5.8 2.2 virginica
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
</code></pre> |
12,125,880 | changing default x range in histogram matplotlib | <p>I would like to change the default x range for the histogram plot. The range of the data is from 7 to 12. However, by default the histogram starts right at 7 and ends at 13. I want it to start at 6.5 and end at 12.5. However, the ticks should go from 7 to 12.How do I do it? </p>
<pre><code>import asciitable
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import pylab
from pylab import xticks
data = asciitable.read(file)
hmag = data['col8']
visits = data['col14']
origin = data['col13']
n, bins, patches = plt.hist(hmag, 30, facecolor='gray', align='mid')
xticks(range(7,13))
pylab.rc("axes", linewidth=8.0)
pylab.rc("lines", markeredgewidth=2.0)
plt.xlabel('H mag', fontsize=14)
plt.ylabel('# of targets', fontsize=14)
pylab.xticks(fontsize=15)
pylab.yticks(fontsize=15)
plt.grid(True)
plt.savefig('hmag_histogram.eps', facecolor='w', edgecolor='w', format='eps')
plt.show()
</code></pre> | 12,126,513 | 3 | 0 | null | 2012-08-25 21:42:57 UTC | 9 | 2019-07-11 14:03:56.483 UTC | null | null | null | null | 1,625,098 | null | 1 | 53 | python|matplotlib|histogram|xrange | 174,756 | <pre><code>plt.hist(hmag, 30, range=[6.5, 12.5], facecolor='gray', align='mid')
</code></pre> |
3,592,212 | Beginning Haskell - getting "not in scope: data constructor" error | <p>I'm going through the problems in the Haskell O'Reilly book. The problem I am working on is </p>
<pre><code>Using the binary tree type that we defined earlier in this chapter,
write a function that will determine the height of the tree. The height
is the largest number of hops from the root to an Empty. For example, the
tree Empty has height zero; Node "x" Empty Empty has height one;
Node "x" Empty (Node "y" Empty Empty) has height two; and so on.
</code></pre>
<p>I'm writing my code in a file called ch3.hs. Here's my code:</p>
<pre><code>36 data Tree a = Node a (Tree a) (Tree a)
37 | Empty
38 deriving (Show)
39
40 --problem 9:Determine the height of a tree
41 height :: Tree -> Int
42 height (Tree node left right) = if (left == Empty && right == Empty) then 0 else max (height left) (height right)
</code></pre>
<p>opening ghci in the terminal and typing :load ch3.hs. When I do that I get the following error:</p>
<pre><code>Prelude> :load ch3.hs
[1 of 1] Compiling Main ( ch3.hs, interpreted )
ch3.hs:42:7: Not in scope: data constructor `Tree'
Failed, modules loaded: none.
</code></pre>
<p>I expect that the Tree data constructor should be there, because I defined it in the lines above the height method. But when I try to load the file, I'm told that the data constructor is not in scope. I appreciate your help and explanation of why this error occurs. Thanks,
Kevin</p> | 3,592,233 | 3 | 0 | null | 2010-08-28 19:56:14.567 UTC | 5 | 2014-07-11 20:41:43.027 UTC | 2011-06-20 16:22:11.487 UTC | null | 329,700 | null | 329,700 | null | 1 | 22 | haskell|scope | 46,888 | <p>Change</p>
<pre><code>height (Tree node left right)
</code></pre>
<p>to</p>
<pre><code>height (Node node left right)
</code></pre>
<p>That means the pattern matching works on the constructors of the <a href="http://en.wikipedia.org/wiki/Algebraic_data_type" rel="noreferrer">algebraic data type</a> (ADT). <code>Tree</code> is not a constructor, it is the name of the ADT.</p>
<p>Btw, you have to comment out your function signature declaration to compile the code because it contains an error.</p>
<p>You can then check the inferred type via</p>
<pre>
:t height
</pre>
<p>in <a href="http://www.haskell.org/ghc/docs/latest/html/users_guide/ghci.html#ghci-introduction" rel="noreferrer">ghci</a> or <a href="http://www.haskell.org/hugs/" rel="noreferrer">hugs</a>.</p> |
22,845,574 | How to dynamically do filtering in Java 8? | <p>I know in Java 8, I can do filtering like this :</p>
<pre><code>List<User> olderUsers = users.stream().filter(u -> u.age > 30).collect(Collectors.toList());
</code></pre>
<p>But what if I have a collection and half a dozen filtering criteria, and I want to test the combination of the criteria ?</p>
<p>For example I have a collection of objects and the following criteria : </p>
<pre><code><1> Size
<2> Weight
<3> Length
<4> Top 50% by a certain order
<5> Top 20% by a another certain ratio
<6> True or false by yet another criteria
</code></pre>
<p>And I want to test the combination of the above criteria, something like :</p>
<pre><code><1> -> <2> -> <3> -> <4> -> <5>
<1> -> <2> -> <3> -> <5> -> <4>
<1> -> <2> -> <5> -> <4> -> <3>
...
<1> -> <5> -> <3> -> <4> -> <2>
<3> -> <2> -> <1> -> <4> -> <5>
...
<5> -> <4> -> <3> -> <3> -> <1>
</code></pre>
<p>If each testing order may give me different results, how to write a loop to automatically filter through all the combinations ?</p>
<p>What I can think of is to use another method that generates the testing order like the following :</p>
<pre><code>int[][] getTestOrder(int criteriaCount)
{
...
}
So if the criteriaCount is 2, it will return : {{1,2},{2,1}}
If the criteriaCount is 3, it will return : {{1,2,3},{1,3,2},{2,1,3},{2,3,1},{3,1,2},{3,2,1}}
...
</code></pre>
<p>But then how to most efficiently implement it with the filtering mechanism in concise expressions that comes with Java 8 ?</p> | 22,855,465 | 2 | 5 | null | 2014-04-03 18:07:00.94 UTC | 33 | 2014-04-08 00:17:47.477 UTC | 2014-04-06 21:28:08.267 UTC | null | 32,834 | null | 32,834 | null | 1 | 48 | java|lambda|filtering|java-8 | 26,023 | <p>Interesting problem. There are several things going on here. No doubt this could be solved in less than half a page of Haskell or Lisp, but this is Java, so here we go....</p>
<p>One issue is that we have a variable number of filters, whereas most of the examples that have been shown illustrate fixed pipelines.</p>
<p>Another issue is that some of the OP's "filters" are context sensitive, such as "top 50% by a certain order". This can't be done with a simple <code>filter(predicate)</code> construct on a stream.</p>
<p>The key is to realize that, while lambdas allow functions to be passed as arguments (to good effect) it also means that they can be stored in data structures and computations can be performed on them. The most common computation is to take multiple functions and compose them.</p>
<p>Assume that the values being operated on are instances of Widget, which is a POJO that has some obvious getters:</p>
<pre><code>class Widget {
String name() { ... }
int length() { ... }
double weight() { ... }
// constructors, fields, toString(), etc.
}
</code></pre>
<p>Let's start off with the first issue and figure out how to operate with a variable number of simple predicates. We can create a list of predicates like this:</p>
<pre><code>List<Predicate<Widget>> allPredicates = Arrays.asList(
w -> w.length() >= 10,
w -> w.weight() > 40.0,
w -> w.name().compareTo("c") > 0);
</code></pre>
<p>Given this list, we can permute them (probably not useful, since they're order independent) or select any subset we want. Let's say we just want to apply all of them. How do we apply a variable number of predicates to a stream? There is a <code>Predicate.and()</code> method that will take two predicates and combine them using a logical <em>and</em>, returning a single predicate. So we could take the first predicate and write a loop that combines it with the successive predicates to build up a single predicate that's a composite <em>and</em> of them all:</p>
<pre><code>Predicate<Widget> compositePredicate = allPredicates.get(0);
for (int i = 1; i < allPredicates.size(); i++) {
compositePredicate = compositePredicate.and(allPredicates.get(i));
}
</code></pre>
<p>This works, but it fails if the list is empty, and since we're doing functional programming now, mutating a variable in a loop is declassé. But lo! This is a reduction! We can reduce all the predicates over the <em>and</em> operator get a single composite predicate, like this:</p>
<pre><code>Predicate<Widget> compositePredicate =
allPredicates.stream()
.reduce(w -> true, Predicate::and);
</code></pre>
<p>(Credit: I learned this technique from <a href="https://twitter.com/venkat_s" rel="noreferrer">@venkat_s</a>. If you ever get a chance, go see him speak at a conference. He's good.)</p>
<p>Note the use of <code>w -> true</code> as the identity value of the reduction. (This could also be used as the initial value of <code>compositePredicate</code> for the loop, which would fix the zero-length list case.)</p>
<p>Now that we have our composite predicate, we can write out a short pipeline that simply applies the composite predicate to the widgets:</p>
<pre><code>widgetList.stream()
.filter(compositePredicate)
.forEach(System.out::println);
</code></pre>
<h2>Context Sensitive Filters</h2>
<p>Now let's consider what I referred to as a "context sensitive" filter, which is represented by the example like "top 50% in a certain order", say the top 50% of widgets by weight. "Context sensitive" isn't the best term for this but it's what I've got at the moment, and it is somewhat descriptive in that it's relative to the number of elements in the stream up to this point.</p>
<p>How would we implement something like this using streams? Unless somebody comes up with something really clever, I think we have to collect the elements somewhere first (say, in a list) before we can emit the first element to the output. It's kind of like <code>sorted()</code> in a pipeline which can't tell which is the first element to output until it has read every single input element and has sorted them.</p>
<p>The straightforward approach to finding the top 50% of widgets by weight, using streams, would look something like this:</p>
<pre><code>List<Widget> temp =
list.stream()
.sorted(comparing(Widget::weight).reversed())
.collect(toList());
temp.stream()
.limit((long)(temp.size() * 0.5))
.forEach(System.out::println);
</code></pre>
<p>This isn't complicated, but it's a bit cumbersome as we have to collect the elements into a list and assign it to a variable, in order to use the list's size in the 50% computation.</p>
<p>This is limiting, though, in that it's a "static" representation of this kind of filtering. How would we chain this into a stream with a variable number of elements (other filters or criteria) like we did with the predicates?</p>
<p>A important observation is that this code does its actual work in between the consumption of a stream and the emitting of a stream. It happens to have a collector in the middle, but if you chain a stream to its front and chain stuff off its back end, nobody is the wiser. In fact, the standard stream pipeline operations like <code>map</code> and <code>filter</code> each take a stream as input and emit a stream as output. So we can write a function kind of like this ourselves:</p>
<pre><code>Stream<Widget> top50PercentByWeight(Stream<Widget> stream) {
List<Widget> temp =
stream.sorted(comparing(Widget::weight).reversed())
.collect(toList());
return temp.stream()
.limit((long)(temp.size() * 0.5));
}
</code></pre>
<p>A similar example might be to find the shortest three widgets:</p>
<pre><code>Stream<Widget> shortestThree(Stream<Widget> stream) {
return stream.sorted(comparing(Widget::length))
.limit(3);
}
</code></pre>
<p>Now we can write something that combines these stateful filters with ordinary stream operations:</p>
<pre><code>shortestThree(
top50PercentByWeight(
widgetList.stream()
.filter(w -> w.length() >= 10)))
.forEach(System.out::println);
</code></pre>
<p>This works, but is kind of lousy because it reads "inside-out" and backwards. The stream source is <code>widgetList</code> which is streamed and filtered through an ordinary predicate. Now, going backwards, the top 50% filter is applied, then the shortest-three filter is applied, and finally the stream operation <code>forEach</code> is applied at the end. This works but is quite confusing to read. And it's still static. What we really want is to have a way to put these new filters inside a data structure that we can manipulate, for example, to run all the permutations, as in the original question.</p>
<p>A key insight at this point is that these new kinds of filters are really just functions, and we have functional interface types in Java which let us represent functions as objects, to manipulate them, store them in data structures, compose them, etc. The functional interface type that takes an argument of some type and returns a value of the same type is <code>UnaryOperator</code>. The argument and return type in this case is <code>Stream<Widget></code>. If we were to take method references such as <code>this::shortestThree</code> or <code>this::top50PercentByWeight</code>, the types of the resulting objects would be</p>
<pre><code>UnaryOperator<Stream<Widget>>
</code></pre>
<p>If we were to put these into a list, the type of that list would be</p>
<pre><code>List<UnaryOperator<Stream<Widget>>>
</code></pre>
<p>Ugh! Three levels of nested generics is too much for me. (But <a href="https://stackoverflow.com/users/2613885/aleksey-shipilev">Aleksey Shipilev</a> did once show me some code that used four levels of nested generics.) The solution for too much generics is to define our own type. Let's call one of our new things a Criterion. It turns out that there's little value to be gained by making our new functional interface type be related to <code>UnaryOperator</code>, so our definition can simply be:</p>
<pre><code>@FunctionalInterface
public interface Criterion {
Stream<Widget> apply(Stream<Widget> s);
}
</code></pre>
<p>Now we can create a list of criteria like this:</p>
<pre><code>List<Criterion> criteria = Arrays.asList(
this::shortestThree,
this::lengthGreaterThan20
);
</code></pre>
<p>(We'll figure out how to use this list below.) This is a step forward, since we can now manipulate the list dynamically, but it's still somewhat limiting. First, it can't be combined with ordinary predicates. Second, there's a lot of hard-coded values here, such as the shortest three: how about two or four? How about a different criterion than length? What we really want is a function that creates these Criterion objects for us. This is easy with lambdas.</p>
<p>This creates a criterion that selects the top N widgets, given a comparator:</p>
<pre><code>Criterion topN(Comparator<Widget> cmp, long n) {
return stream -> stream.sorted(cmp).limit(n);
}
</code></pre>
<p>This creates a criterion that selects the top p percent of widgets, given a comparator:</p>
<pre><code>Criterion topPercent(Comparator<Widget> cmp, double pct) {
return stream -> {
List<Widget> temp =
stream.sorted(cmp).collect(toList());
return temp.stream()
.limit((long)(temp.size() * pct));
};
}
</code></pre>
<p>And this creates a criterion from an ordinary predicate:</p>
<pre><code>Criterion fromPredicate(Predicate<Widget> pred) {
return stream -> stream.filter(pred);
}
</code></pre>
<p>Now we have a very flexible way of creating criteria and putting them into a list, where they can be subsetted or permuted or whatever:</p>
<pre><code>List<Criterion> criteria = Arrays.asList(
fromPredicate(w -> w.length() > 10), // longer than 10
topN(comparing(Widget::length), 4L), // longest 4
topPercent(comparing(Widget::weight).reversed(), 0.50) // heaviest 50%
);
</code></pre>
<p>Once we have a list of Criterion objects, we need to figure out a way to apply all of them. Once again, we can use our friend <code>reduce</code> to combine all of them into a single Criterion object:</p>
<pre><code>Criterion allCriteria =
criteria.stream()
.reduce(c -> c, (c1, c2) -> (s -> c2.apply(c1.apply(s))));
</code></pre>
<p>The identity function <code>c -> c</code> is clear, but the second arg is a bit tricky. Given a stream <code>s</code> we first apply Criterion c1, then Criterion c2, and this is wrapped in a lambda that takes two Criterion objects c1 and c2 and returns a lambda that applies the composition of c1 and c2 to a stream and returns the resulting stream.</p>
<p>Now that we've composed all the criteria, we can apply it to a stream of widgets like so:</p>
<pre><code>allCriteria.apply(widgetList.stream())
.forEach(System.out::println);
</code></pre>
<p>This is still a bit inside-out, but it's fairly well controlled. Most importantly, it addresses the original question, which is how to combine criteria dynamically. Once the Criterion objects are in a data structure, they can be selected, subsetted, permuted, or whatever as necessary, and they can all be combined in a single criterion and applied to a stream using the above techniques.</p>
<p>The functional programming gurus are probably saying "He just reinvented ... !" which is probably true. I'm sure this has probably been invented somewhere already, but it's new to Java, because prior to lambda, it just wasn't feasible to write Java code that uses these techniques.</p>
<h2>Update 2014-04-07</h2>
<p>I've cleaned up and posted the complete <a href="https://gist.github.com/stuart-marks/10076102" rel="noreferrer">sample code</a> in a gist.</p> |
20,828,179 | Angular unit-test controllers - mocking service inside controller | <p>I have the following situation:</p>
<p><strong>controller.js</strong></p>
<pre><code>controller('PublishersCtrl',['$scope','APIService','$timeout', function($scope,APIService,$timeout) {
APIService.get_publisher_list().then(function(data){
});
}));
</code></pre>
<p><strong>controllerSpec.js</strong></p>
<pre><code>'use strict';
describe('controllers', function(){
var scope, ctrl, timeout;
beforeEach(module('controllers'));
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new(); // this is what you missed out
timeout = {};
controller = $controller('PublishersCtrl', {
$scope: scope,
APIService: APIService,
$timeout: timeout
});
}));
it('should have scope variable equals number', function() {
expect(scope.number).toBe(3);
});
});
</code></pre>
<p><strong>Error:</strong></p>
<pre><code> TypeError: Object #<Object> has no method 'get_publisher_list'
</code></pre>
<p>I also tried something like this, and it didn't work:</p>
<pre><code>describe('controllers', function(){
var scope, ctrl, timeout,APIService;
beforeEach(module('controllers'));
beforeEach(module(function($provide) {
var service = {
get_publisher_list: function () {
return true;
}
};
$provide.value('APIService', service);
}));
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
timeout = {};
controller = $controller('PublishersCtrl', {
$scope: scope,
APIService: APIService,
$timeout: timeout
}
);
}));
it('should have scope variable equals number', function() {
spyOn(service, 'APIService');
scope.get_publisher_list();
expect(scope.number).toBe(3);
});
});
</code></pre>
<p>How can i solve this? any suggestions?</p> | 20,830,042 | 1 | 3 | null | 2013-12-29 17:43:24.637 UTC | 13 | 2016-07-21 17:11:18.93 UTC | 2015-03-11 12:25:55.343 UTC | null | 345,944 | null | 345,944 | null | 1 | 20 | unit-testing|angularjs|karma-runner|karma-jasmine | 27,603 | <p>There are two ways (or more for sure).</p>
<p>Imagining this kind of service (doesn't matter if it is a factory):</p>
<pre><code>app.service('foo', function() {
this.fn = function() {
return "Foo";
};
});
</code></pre>
<p>With this controller:</p>
<pre><code>app.controller('MainCtrl', function($scope, foo) {
$scope.bar = foo.fn();
});
</code></pre>
<p>One way is just creating an object with the methods you will use and spy them:</p>
<pre><code>foo = {
fn: function() {}
};
spyOn(foo, 'fn').andReturn("Foo");
</code></pre>
<p>Then you pass that <code>foo</code> as a dep to the controller. No need to inject the service. That will work.</p>
<p>The other way is to mock the service and inject the mocked one:</p>
<pre><code>beforeEach(module('app', function($provide) {
var foo = {
fn: function() {}
};
spyOn(foo, 'fn').andReturn('Foo');
$provide.value('foo', foo);
}));
</code></pre>
<p>When you inject then <code>foo</code> it will inject this one.</p>
<p>See it here: <a href="http://plnkr.co/edit/WvUIrtqMDvy1nMtCYAfo?p=preview" rel="noreferrer">http://plnkr.co/edit/WvUIrtqMDvy1nMtCYAfo?p=preview</a></p>
<h3>Jasmine 2.0:</h3>
<p>For those that struggle with making the answer work,</p>
<p>as of Jasmine 2.0 <code>andReturn()</code> became <code>and.returnValue()</code></p>
<p>So for example in the 1st test from the plunker above:</p>
<pre><code>describe('controller: MainCtrl', function() {
var ctrl, foo, $scope;
beforeEach(module('app'));
beforeEach(inject(function($rootScope, $controller) {
foo = {
fn: function() {}
};
spyOn(foo, 'fn').and.returnValue("Foo"); // <----------- HERE
$scope = $rootScope.$new();
ctrl = $controller('MainCtrl', {$scope: $scope , foo: foo });
}));
it('Should call foo fn', function() {
expect($scope.bar).toBe('Foo');
});
});
</code></pre>
<p>(Source: <a href="https://stackoverflow.com/users/4640433/rvandersteen">Rvandersteen</a>)</p> |
22,227,675 | Why NuGet adds app.config with assemblyBinding to LIBRARY projects during a NuGet package update? | <p>Isn't this information necessary only in the executable's project?</p>
<p>How to disable this file creation? </p>
<p>NuGet 2.8</p>
<p><strong>EDIT</strong></p>
<p>Library projects were exceptions in NuGet 2.7, behavior changed in 2.8 by fixing this issue: <a href="http://nuget.codeplex.com/workitem/3827" rel="noreferrer">http://nuget.codeplex.com/workitem/3827</a> with commit: <a href="https://github.com/NuGet/NuGet2/commit/448652d028e3f01ba4022e147baaf4e1fb3f969b" rel="noreferrer">https://github.com/NuGet/NuGet2/commit/448652d028e3f01ba4022e147baaf4e1fb3f969b</a></p> | 22,228,738 | 3 | 5 | null | 2014-03-06 14:41:08.19 UTC | 7 | 2020-04-23 18:22:02.333 UTC | 2018-05-09 21:54:24.213 UTC | null | 1,775,528 | null | 2,755,656 | null | 1 | 59 | nuget | 20,667 | <p>Assembly binding redirects are as valid in a class library as they are in executable projects. </p>
<p>Think about this; when building your application, how will the compiler know which version of referenced assemblies to use (for the class libraries)? </p>
<p>Often this will work just fine, without the redirects, but when you stumble over a machine that has a GAC'ed version of the assembly, you could get into trouble.</p>
<p>I suggest you read the <a href="http://msdn.microsoft.com/en-us/library/7wd6ex19.aspx" rel="nofollow noreferrer">assembly binding redirect documentation</a> to better understand what it is and does.</p>
<p>NuGet adds the app.config with redirects to help you, and quite frankly, I don't get the fuzz about an extra app.config for everything to work as expected.</p>
<p>As of today, it will add redirects to all projects, except the following types:</p>
<ul>
<li>WiX</li>
<li>JS</li>
<li>Nemerle</li>
<li>C++</li>
<li>Synergex</li>
<li>Visual Studio</li>
<li>Windows Store App</li>
</ul>
<p>As far as I know, there's no way of turning this off. You could <a href="https://github.com/NuGet/Home/issues/new" rel="nofollow noreferrer">create an issue at Github</a> if this is a problem.</p>
<p>The source code for adding assembly binding redirects can be found <a href="https://github.com/NuGet/NuGet2/blob/2.13/src/VisualStudio/RuntimeHelpers.cs" rel="nofollow noreferrer">here</a>.</p> |
10,921,645 | SSIS How to get part of a string by separator | <p>I need an SSIS expression to get the left part of a string before the separator, and then put the new string in a new column. I checked in derived column, it seems no such expressions. <code>Substring</code> could only return string part with fixed length. </p>
<p>For example, with separator string <code>-</code> :</p>
<pre><code>Art-Reading Should return Art
Art-Writing Should return Art
Science-chemistry Should return Science
</code></pre>
<p>P.S.
I knew this could be done in MySQL with <code>SUBSTRING_INDEX()</code>, but I'm looking for an equivalent in SSIS, or at least in SQL Server</p> | 10,929,122 | 4 | 1 | null | 2012-06-06 20:21:29.7 UTC | 1 | 2019-03-24 20:27:57.987 UTC | 2019-03-24 20:27:57.987 UTC | null | 7,031,230 | null | 1,317,602 | null | 1 | 16 | sql-server|ssis|expression|etl | 79,929 | <p>of course you can:</p>
<p><img src="https://i.stack.imgur.com/iG6Tz.jpg" alt="enter image description here"></p>
<p>just configure your derived columns like this:</p>
<p><img src="https://i.stack.imgur.com/5QGAB.jpg" alt="enter image description here"></p>
<p>Here is the expression to make your life easier:</p>
<pre><code>SUBSTRING(name,1,FINDSTRING(name,"-",1) - 1)
</code></pre>
<p>FYI, the second "1" means to get the first occurrence of the string "-"</p>
<p>EDIT:
expression to deal with string without "-"</p>
<pre><code>FINDSTRING(name,"-",1) != 0 ? (SUBSTRING(name,1,FINDSTRING(name,"-",1) - 1)) : name
</code></pre> |
10,982,167 | Find an XElement with a certain attribute name and value with LINQ | <pre><code>XDocument xDocument = XDocument.Load("...");
IEnumerable<XElement> elements = xDocument
.Element("lfm")
.Element("events")
.Elements("event");
try
{
foreach (XElement elm in elements)
{
comm.Parameters.AddWithValue("extID", elm.Element("id").Value ?? "");
comm.Parameters.AddWithValue("Title", elm.Element("title").Value ?? "");
comm.Parameters.AddWithValue("HeadlineArtist",
elm.Element("artists").Element("headliner").Value ?? "");
</code></pre>
<p>but I want the value of the element "image" with the attribute "size=large", I have been looking all night, and this is the closest I have come:</p>
<pre><code>comm.Parameters.AddWithValue("LargeImage",
elm.Descendants("image")
.FirstOrDefault(i => (string)i.Attribute("size") == "large").Value);
</code></pre>
<p>Sample of the part of XML response:</p>
<pre><code><lfm status="ok">
<events xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
location="Chicago, United States" page="1" perPage="1"
totalPages="341" total="341" festivalsonly="0" tag="">
<event xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
<id>3264699</id>
<title>Iron And Wine</title>
<artists>
<artist>Iron And Wine</artist>
<artist>Dr. John</artist>
<headliner>Iron And Wine</headliner>
</artists>
<venue>
<id>8915382</id>
<name>Ravinia Festival</name>
<location>
<city>Highland Park</city>
<country>United States</country>
<street>200 Ravinia Park Rd</street>
<postalcode>60035</postalcode>
<geo:point>
<geo:lat>42.15831</geo:lat>
<geo:long>-87.778409</geo:long>
</geo:point>
</location>
<url>http://www.last.fm/venue/8915382+Ravinia+Festival</url>
<website>http://www.ravinia.org/</website>
<phonenumber>847.266.5100</phonenumber>
<image size="small">http://userserve-ak.last.fm/serve/34/63026487.jpg</image>
<image size="medium">http://userserve-ak.last.fm/serve/64/63026487.jpg</image>
<image size="large">http://userserve-ak.last.fm/serve/126/63026487.jpg</image>
<image size="extralarge">http://userserve-ak.last.fm/serve/252/63026487.jpg</image>
</code></pre> | 10,982,276 | 2 | 2 | null | 2012-06-11 14:33:21.567 UTC | 2 | 2017-10-02 12:43:07.657 UTC | 2015-02-10 22:54:16.997 UTC | null | 3,204,551 | null | 813,523 | null | 1 | 18 | c#|xml|linq|xelement | 45,496 | <p>Try</p>
<pre><code>XElement result = elm.Descendants("image")
.FirstOrDefault(el => el.Attribute("size") != null &&
el.Attribute("size").Value == "large");
if (result != null) {
process result.Value ...
}
</code></pre>
<p>Starting with C#6.0 (VS 2015), you can write:</p>
<pre><code>XElement result = elm.Descendants("image")
.FirstOrDefault(el => el.Attribute("size")?.Value == "large");
if (result != null) {
process result.Value ...
}
</code></pre>
<p>A non-obvious alternative (as @RandRandom pointed out) is to cast the Attribute to <code>string</code>:</p>
<pre><code>XElement result = elm.Descendants("image")
.FirstOrDefault(el => (string)el.Attribute("size") == "large");
if (result != null) {
process result.Value ...
}
</code></pre>
<p>This works, because because of <a href="https://msdn.microsoft.com/en-us/library/bb339184(v=vs.110).aspx" rel="noreferrer">XAttribute Explicit Conversion (XAttribute to String)</a>.</p> |
11,128,086 | Simple Popularity Algorithm | <h2>Summary</h2>
<p>As Ted Jaspers wisely pointed out, the methodology I described in the original proposal back in 2012 is actually a special case of an <a href="https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average" rel="nofollow noreferrer">exponential moving average</a>. The beauty of this approach is that it can be calculated recursively, meaning you only need to store a single popularity value with each object and then you can recursively adjust this value when an event occurs. There's no need to record every event.</p>
<p>This single popularity value represents all past events (within the limits of the data type being used), but older events begin to matter exponentially less as new events are factored in. This algorithm will adapt to different time scales and will respond to varying traffic volumes. Each time an event occurs, the <strong>new</strong> popularity value can be calculated using the following formula:</p>
<p><code>(a * t) + ((1 - a) * p)</code></p>
<ul>
<li><code>a</code> — coefficient between 0 and 1 (higher values discount older events faster)</li>
<li><code>t</code> — current timestamp</li>
<li><code>p</code> — current popularity value (e.g. stored in a database)</li>
</ul>
<p>Reasonable values for <code>a</code> will depend on your application. A good starting place is <code>a=2/(N+1)</code>, where <code>N</code> is the number of events that should significantly affect the outcome. For example, on a low-traffic website where the event is a page view, you might expect hundreds of page views over a period of a few days. Choosing <code>N=100</code> (<code>a≈0.02</code>) would be a reasonable choice. For a high-traffic website, you might expect millions of page views over a period of a few days, in which case <code>N=1000000</code> (<code>a≈0.000002</code>) would be more reasonable. The value for <code>a</code> will likely need to be gradually adjusted over time.</p>
<p>To illustrate how simple this popularity algorithm is, here's an example of how it can be implemented in Craft CMS in 2 lines of Twig markup:</p>
<pre><code>{% set popularity = (0.02 * date().timestamp) + (0.98 * entry.popularity) %}
{% do entry.setFieldValue("popularity", popularity) %}
</code></pre>
<p>Notice that there's no need to create new database tables or store endless event records in order to calculate popularity.</p>
<p>One caveat to keep in mind is that exponential moving averages have a spin-up interval, so it takes a few recursions before the value can be considered accurate. This means the initial condition is important. For example, if the popularity of a new item is initialized using the current timestamp, the item immediately becomes the most popular item in the entire set before eventually settling down into a more accurate position. This might be desirable if you want to promote new content. Alternatively, you may want content to work its way up from the bottom, in which case you could initialize it with the timestamp of when the application was first launched. You could also find a happy medium by initializing the value with an average of all popularity values in the database, so it starts out right in the middle.</p>
<hr>
<h2>Original Proposal</h2>
<p>There are plenty of <a href="http://blog.linkibol.com/2010/05/07/how-to-build-a-popularity-algorithm-you-can-be-proud-of/" rel="nofollow noreferrer">suggested algorithms</a> for calculating popularity based on an item's age and the number of votes, clicks, or purchases an item receives. However, the more robust methods I've seen often require overly complex calculations and multiple stored values which clutter the database. I've been contemplating an extremely simple algorithm that doesn't require storing <em>any</em> variables (other than the popularity value itself) and requires only <em>one</em> simple calculation. It's ridiculously simple:</p>
<p><strong><code>p = (p + t) / 2</code></strong></p>
<p>Here, <strong>p is the popularity value stored in the database</strong> and <strong>t is the current timestamp</strong>. When an item is first created, <strong>p</strong> must be initialized. There are two possible initialization methods:</p>
<ol>
<li>Initialize <strong>p</strong> with the current timestamp <strong>t</strong></li>
<li>Initialize <strong>p</strong> with the average of all <strong>p</strong> values in the database</li>
</ol>
<p>Note that initialization method (1) gives recently added items a clear advantage over historical items, thus adding an element of <em>relevance</em>. On the other hand, initialization method (2) treats new items as equals when compared to historical items.</p>
<p>Let's say you use initialization method (1) and initialize <strong>p</strong> with the current timestamp. When the item receives its first vote, <strong>p</strong> becomes the average of the creation time and the vote time. Thus, the popularity value <strong>p</strong> still represents a valid timestamp (assuming you round to the nearest integer), but the actual time it represents is abstracted.</p>
<p>With this method, only one simple calculation is required and only one value needs to be stored in the database (<strong>p</strong>). This method also prevents runaway values, since a given item's popularity can never exceed the current time.</p>
<p>An example of the algorithm at work over a period of 1 day: <a href="http://jsfiddle.net/q2UCn/" rel="nofollow noreferrer">http://jsfiddle.net/q2UCn/</a><br />
An example of the algorithm at work over a period of 1 year: <a href="http://jsfiddle.net/tWU9y/" rel="nofollow noreferrer">http://jsfiddle.net/tWU9y/</a></p>
<p>If you expect votes to steadily stream in at sub-second intervals, then you will need to use a microsecond timestamp, such as the PHP <code>microtime()</code> function. Otherwise, a standard UNIX timestamp will work, such as the PHP <code>time()</code> function.</p>
<p>Now for my question: do you see any major flaws with this approach?</p> | 51,670,966 | 5 | 2 | null | 2012-06-20 20:57:53.987 UTC | 16 | 2019-09-10 07:15:17.6 UTC | 2019-09-10 07:15:17.6 UTC | null | 1,060,679 | null | 1,060,679 | null | 1 | 22 | algorithm|popularity | 11,594 | <p>The proposed algorithm is a good approach, and is a special case of an <a href="https://en.wikipedia.org/wiki/Moving_average" rel="nofollow noreferrer">Exponential Moving Average</a> where alpha=0.5:</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>p = alpha*p + (1-alpha)*t = 0.5*p + 0.5*t = (p+t)/2 //(for alpha = 0.5)</code></pre>
</div>
</div>
</p>
<p>A way to tweak the fact that the proposed solution for alpha=0.5 tends to favor recent votes (as noted by daniloquio) is to choose higher values for alpha (e.g. 0.9 or 0.99). Note that applying this to the testcase proposed by daniloquio is <strong>not</strong> working however, because when alpha increases the algorithm needs more 'time' to settle (so the arrays should be longer, which is often true in real applications).</p>
<p>Thus:</p>
<ul>
<li>for alpha=0.9 the algorithm averages approximately the last 10 values</li>
<li>for alpha=0.99 the algorithm averages approximately the last 100 values</li>
<li>for alpha=0.999 the algorithm averages approximately the last 1000 values</li>
<li>etc.</li>
</ul> |
10,949,730 | Is it possible to for SQL Output clause to return a column not being inserted? | <p>I've made some modifications to my database and I need to migrate the old data to the new tables. For that, I need to fill a table (ReportOptions) taking the data from the original table (Practice), and fill a second intermediate table (PracticeReportOption).</p>
<pre><code>ReportOption (ReportOptionId int PK, field1, field2...)
Practice (PracticeId int PK, field1, field2...)
PracticeReportOption (PracticeReportOptionId int PK, PracticeId int FK, ReportOptionId int FK, field1, field2...)
</code></pre>
<p>I made a query to get all the data I need to move from Practice to ReportOptions, but I'm having trouble to fill the intermediate table</p>
<pre><code>--Auxiliary tables
DECLARE @ReportOption TABLE (PracticeId int /*This field is not on the actual ReportOption table*/, field1, field2...)
DECLARE @PracticeReportOption TABLE (PracticeId int, ReportOptionId int, field1, field2)
--First I get all the data I need to move
INSERT INTO @ReportOption
SELECT P.practiceId, field1, field2...
FROM Practice P
--I insert it into the new table, but somehow I need to have the repation PracticeId / ReportOptionId
INSERT INTO ReportOption (field1, field2...)
OUTPUT @ReportOption.PracticeId, --> this is the field I don't know how to get
inserted.ReportOptionId
INTO @PracticeReportOption (PracticeId, ReportOptionId)
SELECT field1, field2
FROM @ReportOption
--This would insert the relationship, If I knew how to get it!
INSERT INTO @PracticeReportOption (PracticeId, ReportOptionId)
SELECT PracticeId, ReportOptionId
FROM @ReportOption
</code></pre>
<p>If I could reference a field that is not on the destination table on the OUTPUT clause, that would be great (I think I can't, but I don't know for sure). Any ideas on how to accomplish my need?</p> | 10,950,418 | 2 | 2 | null | 2012-06-08 13:23:46.07 UTC | 55 | 2020-01-19 01:15:42.14 UTC | 2019-06-21 09:03:55.603 UTC | null | 133 | null | 1,019,193 | null | 1 | 153 | sql|sql-server | 54,235 | <p>You can do this by using <code>MERGE</code> instead of insert:</p>
<p>so replace this</p>
<pre><code>INSERT INTO ReportOption (field1, field2...)
OUTPUT @ReportOption.PracticeId, --> this is the field I don't know how to get
inserted.ReportOptionId
INTO @PracticeReportOption (PracticeId, ReportOptionId)
SELECT field1, field2
FROM @ReportOption
</code></pre>
<p>with </p>
<pre><code>MERGE INTO ReportOption USING @ReportOption AS temp ON 1 = 0
WHEN NOT MATCHED THEN
INSERT (field1, field2)
VALUES (temp.Field1, temp.Field2)
OUTPUT temp.PracticeId, inserted.ReportOptionId, inserted.Field1, inserted.Field2
INTO @PracticeReportOption (PracticeId, ReportOptionId, Field1, Field2);
</code></pre>
<p>The key is to use a predicate that will never be true (1 = 0) in the merge search condition, so you will always perform the insert, but have access to fields in both the source and destination tables.</p>
<hr>
<p>Here is the entire code I used to test it:</p>
<pre><code>CREATE TABLE ReportOption (ReportOptionID INT IDENTITY(1, 1), Field1 INT, Field2 INT)
CREATE TABLE Practice (PracticeID INT IDENTITY(1, 1), Field1 INT, Field2 INT)
CREATE TABLE PracticeReportOption (PracticeReportOptionID INT IDENTITY(1, 1), PracticeID INT, ReportOptionID INT, Field1 INT, Field2 INT)
INSERT INTO Practice VALUES (1, 1), (2, 2), (3, 3), (4, 4)
MERGE INTO ReportOption r USING Practice p ON 1 = 0
WHEN NOT MATCHED THEN
INSERT (field1, field2)
VALUES (p.Field1, p.Field2)
OUTPUT p.PracticeId, inserted.ReportOptionId, inserted.Field1, inserted.Field2
INTO PracticeReportOption (PracticeId, ReportOptionId, Field1, Field2);
SELECT *
FROM PracticeReportOption
DROP TABLE ReportOption
DROP TABLE Practice
DROP TABLE PracticeReportOption
</code></pre>
<hr>
<p>More reading, and the source of all that I know on the subject is <a href="http://dataeducation.com/dr-output-or-how-i-learned-to-stop-worrying-and-love-the-merge/" rel="noreferrer">Here</a></p> |
13,218,975 | error mysql : Got a packet bigger than 'max_allowed_packet' bytes | <p>for import mysql database give me this error :</p>
<pre><code>$ `mysql -u user -p password zxc_db < zxc.sql`
ERROR 1153 (08S01) at line 96: Got a packet bigger than 'max_allowed_packet' bytes
</code></pre>
<p>Please give me a best solution to solve it ?
tanx .</p> | 13,219,033 | 1 | 2 | null | 2012-11-04 13:33:56.393 UTC | 2 | 2013-09-12 17:01:04.59 UTC | null | null | null | null | 1,624,348 | null | 1 | 7 | mysql|mysqldump|mysql-error-1064 | 40,252 | <p>the best solution is " change mysql.cnf "
debian :
/etc/mysql/mysql.cnf
change this line ==> <code>max_allowed_packet = 16M</code>
to : <code>max_allowed_packet = 128M</code></p>
<p>or
add --max_allowed_packet=128M to your mysqldump command.</p>
<pre><code>mysql --max_allowed_packet=128M -u user -ppass database < database.sql
</code></pre> |
12,816,075 | JavaFx GridPane - how to center elements | <p>I have a <code>GridPane</code> filled with 1-letter-labels.</p>
<p>Here is an image:</p>
<p><a href="https://i.stack.imgur.com/T5npB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T5npB.jpg" alt="image"></a>
</p>
<p>Here is the code:</p>
<pre><code>int charSpacing = 1;
int charsInWidth = 28;
int charsInHeight = 16;
double charWidth = 15;
double charHeight = 20;
GridPane gp = new GridPane();
gp.setAlignment(Pos.CENTER);
Label[] tmp = new Label[charsInHeight*charsInWidth];
String text = "W";
int currArrPos = 0;
for(int y = 0; y < charsInHeight; y++) {
HBox hbox = new HBox(charSpacing);
for(int x = 0; x < charsInWidth; x++) {
tmp[currArrPos] = new Label(text);
tmp[currArrPos].setTextFill(Paint.valueOf("white"));
tmp[currArrPos].setMinHeight(charHeight);
tmp[currArrPos].setMinWidth(charWidth);
tmp[currArrPos].setMaxHeight(charHeight);
tmp[currArrPos].setMaxWidth(charWidth);
tmp[currArrPos].setStyle("-fx-border-color: white;");
hbox.getChildren().add(tmp[currArrPos++]);
if(x%2 == 0){
text = "I";
} else{
text = "W";
}
}
gp.add(hbox, 1, y);
}
guiDisplay.getChildren().add(gp);
</code></pre>
<p>How can I center the characters? </p>
<p>I have put them in a <code>HBox</code> and gave them spacing. I tried to make the <code>textAlignment</code> of the label to <code>CENTER</code>, but that doesn't work of course. </p>
<p>I tried this also:</p>
<pre><code>gp.setAlignment(Pos.CENTER);
</code></pre>
<p>Has anybody an idea? Thanks!</p> | 12,816,318 | 3 | 0 | null | 2012-10-10 09:25:41.473 UTC | 2 | 2019-08-25 13:24:46.67 UTC | 2019-08-25 13:24:46.67 UTC | null | 4,751,173 | null | 1,347,198 | null | 1 | 11 | java|user-interface|positioning|javafx-2|gridpanel | 56,311 | <p>oh, that was easy. i did the alignment on the wrong place. adding this will do the job:</p>
<pre><code>tmp[currArrPos].setAlignment(Pos.CENTER);
</code></pre>
<p>thanks anyway.</p> |
13,050,003 | Apply function to pandas DataFrame that can return multiple rows | <p>I am trying to transform DataFrame, such that some of the rows will be replicated a given number of times. For example:</p>
<pre><code>df = pd.DataFrame({'class': ['A', 'B', 'C'], 'count':[1,0,2]})
class count
0 A 1
1 B 0
2 C 2
</code></pre>
<p>should be transformed to:</p>
<pre><code> class
0 A
1 C
2 C
</code></pre>
<p>This is the reverse of aggregation with count function. Is there an easy way to achieve it in pandas (without using for loops or list comprehensions)? </p>
<p>One possibility might be to allow <code>DataFrame.applymap</code> function return multiple rows (akin <code>apply</code> method of <code>GroupBy</code>). However, I do not think it is possible in pandas now.</p> | 13,052,373 | 4 | 2 | null | 2012-10-24 13:14:11.267 UTC | 9 | 2020-01-01 12:55:13.99 UTC | 2019-01-04 11:05:12 UTC | null | 4,909,087 | null | 74,342 | null | 1 | 21 | python|pandas|dataframe | 21,001 | <p>You could use groupby:</p>
<pre><code>def f(group):
row = group.irow(0)
return DataFrame({'class': [row['class']] * row['count']})
df.groupby('class', group_keys=False).apply(f)
</code></pre>
<p>so you get</p>
<pre><code>In [25]: df.groupby('class', group_keys=False).apply(f)
Out[25]:
class
0 A
0 C
1 C
</code></pre>
<p>You can fix the index of the result however you like</p> |
13,082,149 | In Xcode project target build settings, What is Mach-O Type? | <p>After getting tired of numerous Match-O linker error, I want to know that this thing means. Instead of trial and error solution, I would like to know the concept behind these things. Specifically I want to know the difference between :</p>
<ol>
<li>Executable</li>
<li>Dynamic Library</li>
<li>Bundle</li>
<li>Static Library</li>
<li>Relocatable Object File</li>
</ol>
<p>These are the options presented when I click on Mach-O Type settings on Linking section. Some small definition or some link to appropriate content is ok too. </p> | 13,082,437 | 2 | 1 | null | 2012-10-26 06:50:58.953 UTC | 13 | 2019-09-01 08:55:58.507 UTC | null | null | null | null | 341,800 | null | 1 | 34 | objective-c|ios|xcode|linker|llvm | 17,353 | <p><a href="http://en.wikipedia.org/wiki/Mach-O" rel="noreferrer">Mach-O</a>, short for Mach object file format, is a file format for executables, object code, shared libraries, dynamically-loaded code, and core dumps. For unix users this is like <code>a.out</code> but with improvements. This is the format used in Mac OS X and iPhone OS libraries for executable files.</p>
<p>As you know iOS devices (iPhone, iPad etc.) have different architectures ARMv6 (iPhone 2G + 3G, iPod Touch) and ARMv7 (iPhone 3GS, iPod Touch 2G + 3G) but the simulators used in Xcode runs mostly on i386 platform. This means the that the library clients have to setup separate targets for the simulator and device. The separate targets duplicate most information, and only differ in the static libraries included. So if you are getting a Mach-O linker error what it means is that xcode is having trouble linking to one of the libraries for that target device; as a result of which compilation fails.</p>
<p>Now your definitions - </p>
<ol>
<li>Executable - compiled machine targeted program ready to be run in binary format. </li>
<li>Dynamic Library - are linked during runtime -- a program with references to a dynamic library will load and link with the library when it starts up (or on demand).</li>
<li>Bundles - and bundle identifier let iOS and OSX recognise any updates to your app. It gives it a unique presence in the app.</li>
<li>Static Library - files are linked at build time. code is copied into the executable. Code in the library that isn't referenced by your program is removed. A program with only static libraries doesn't have any dependencies during runtime.</li>
<li>Relocatable Object File - is another word for a dynamic library. When you link with a dynamic library, the addresses of the functions contained within are computed, based on where the library is loaded in memory. They are "relocatable" because the addresses of the contained functions are not determined at link time. (In a static library, the addresses are computed during link time.)</li>
</ol> |
12,758,088 | Installer and Updater for a python desktop application | <p>I am building a desktop app with python and packaging it to an exe with Pyinstaller.
I would like to ship my application with an installer and also provide automatic and silent updates to the software like Google Chrome, Dropbox or Github for Windows does.</p>
<p>I have found the following software to be able to do this:</p>
<ul>
<li><a href="http://code.google.com/p/omaha/" rel="noreferrer">Google Omaha</a> - Does not provide a server</li>
<li><a href="https://github.com/github/Shimmer" rel="noreferrer">Github Shimmer</a> - The perfect solution but Paul told me it can't handle non .Net apps yet</li>
<li><a href="http://winsparkle.org/" rel="noreferrer">WinSparkle</a> - Updater only.</li>
<li><a href="http://netsparkle.codeplex.com/" rel="noreferrer">NetSparkle</a> - As the name suggests very .Net focused</li>
<li><a href="http://nsis.sourceforge.net/Main_Page" rel="noreferrer">NSIS</a> - Installer.</li>
<li><a href="http://msdn.microsoft.com/en-us/library/142dbbz4(v=vs.80).aspx" rel="noreferrer">ClickOnce</a> - .NET only</li>
</ul>
<p>I am trying to find the easiest solution to my problem.</p> | 12,823,983 | 4 | 4 | null | 2012-10-06 08:25:06.157 UTC | 18 | 2015-07-18 03:41:21.073 UTC | 2012-10-06 10:20:11.403 UTC | null | 19,929 | null | 19,929 | null | 1 | 39 | python|windows|nsis|auto-update|pyinstaller | 10,770 | <p>There is a suite of tools from the cloudmatrix guys that addresses that problem. </p>
<p><a href="http://pypi.python.org/pypi/esky">esky</a> is an auto-update framework for frozen apps that is compatible with the common python "packaging" frameworks. <a href="http://pypi.python.org/pypi/signedimp/0.3.2">signedimp</a> tries to ensure that apps are not modified after they are signed, and to minimize invasive Windows UAC dialogs. <a href="http://pypi.python.org/pypi/myppy/0.1.0">myppy</a> aims to insulate you from base library incompatibility issues on Linux eg installing on distributions with different gcc and libc versions. The whole set can be seen on github <a href="https://github.com/cloudmatrix/">here</a>. </p>
<p>The video and slides from this year's PyCon are here: <a href="http://lanyrd.com/2012/pycon/spckh/">http://lanyrd.com/2012/pycon/spckh/</a></p> |
12,765,833 | Counting the number of True Booleans in a Python List | <p>I have a list of Booleans:</p>
<pre><code>[True, True, False, False, False, True]
</code></pre>
<p>and I am looking for a way to count the number of <code>True</code> in the list (so in the example above, I want the return to be <code>3</code>.) I have found examples of looking for the number of occurrences of specific elements, but is there a more efficient way to do it since I'm working with Booleans? I'm thinking of something analogous to <code>all</code> or <code>any</code>.</p> | 12,765,840 | 8 | 0 | null | 2012-10-07 03:12:41.943 UTC | 15 | 2020-04-13 04:10:18.637 UTC | 2015-06-01 11:23:16.853 UTC | null | 1,173,112 | null | 1,702,140 | null | 1 | 187 | python|list|boolean|counting | 208,429 | <p><code>True</code> is equal to <code>1</code>.</p>
<pre><code>>>> sum([True, True, False, False, False, True])
3
</code></pre> |
16,638,813 | javax.security.auth.login.LoginException: No LoginModules configured for SomeLogin | <p>Well I'm trying to create JAAS authentication for my Servlet (running on Tomcat 7 in Eclipse), but I'm getting this error.</p>
<p>He're's the complete stack trace:
'`</p>
<pre><code>INFO: Starting Servlet Engine: Apache Tomcat/7.0.32
Geg 19, 2013 9:53:08 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Geg 19, 2013 9:53:08 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Geg 19, 2013 9:53:08 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1786 ms
Geg 19, 2013 9:53:30 PM org.apache.catalina.realm.JAASRealm authenticate
SEVERE: Unexpected error
javax.security.auth.login.LoginException: No LoginModules configured for GdiaLogin
at javax.security.auth.login.LoginContext.init(Unknown Source)
at javax.security.auth.login.LoginContext.<init>(Unknown Source)
at org.apache.catalina.realm.JAASRealm.authenticate(JAASRealm.java:392)
at org.apache.catalina.realm.JAASRealm.authenticate(JAASRealm.java:332)
at org.apache.catalina.authenticator.BasicAuthenticator.authenticate(BasicAuthenticator.java:158)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:544)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Geg 19, 2013 10:29:20 PM org.apache.catalina.realm.JAASRealm authenticate
SEVERE: Unexpected error
javax.security.auth.login.LoginException: No LoginModules configured for GdiaLogin
at javax.security.auth.login.LoginContext.init(Unknown Source)
at javax.security.auth.login.LoginContext.<init>(Unknown Source)
at org.apache.catalina.realm.JAASRealm.authenticate(JAASRealm.java:392)
at org.apache.catalina.realm.JAASRealm.authenticate(JAASRealm.java:332)
at org.apache.catalina.authenticator.BasicAuthenticator.authenticate(BasicAuthenticator.java:158)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:544)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
</code></pre>
<p>`</p>
<p>In context.xml:</p>
<pre><code><Realm className="org.apache.catalina.realm.JAASRealm"
appName="GdiaLogin"
userClassNames="org.ktu.gdia.core.security.UserPrincipal"
roleClassNames="org.ktu.gdia.core.security.RolePrincipal" />
</code></pre>
<p>In jaas.config (I'm pretty sure Tomcat finds it correctly because I added the correct path with arguments for "run configurations" in eclipse):</p>
<pre><code> GdiaLogin {
org.ktu.gdia.core.security.GdiaLoginModule required debug=true;
};
</code></pre>
<p>I'm assuming there has to be something wrong with the jaas.config...</p>
<p>My Login Module, not sure if I need to provide it here, though, it's almost straight from a tutorial I've been following:</p>
<pre><code> package org.ktu.gdia.core.security;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
import org.ktu.gdia.core.businesslogic.ControllerFactory;
import org.ktu.gdia.core.interfaces.SecurityControllerInterface;
public class GdiaLoginModule implements LoginModule {
private CallbackHandler handler;
private Subject subject;
private UserPrincipal userPrincipal;
private RolePrincipal rolePrincipal;
private String login;
private List<String> userGroups;
private SecurityControllerInterface securityController;
@Override
public void initialize(Subject subject, CallbackHandler callbackHandler,
Map<String, ?> sharedState, Map<String, ?> options) {
try {
securityController = ControllerFactory.getInstance().getSecurityController();
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException e) {
throw new RuntimeException("Failed to initialize SecurityController in " + this.getClass().getSimpleName(), e);
}
handler = callbackHandler;
this.subject = subject;
}
@Override
public boolean login() throws LoginException {
Callback[] callbacks = new Callback[2];
callbacks[0] = new NameCallback("login");
callbacks[1] = new PasswordCallback("password", true);
try {
handler.handle(callbacks);
String name = ((NameCallback) callbacks[0]).getName();
String password = String.valueOf(((PasswordCallback) callbacks[1])
.getPassword());
// Here we validate the credentials against some
// authentication/authorization provider.
// It can be a Database, an external LDAP,
// a Web Service, etc.
// For this tutorial we are just checking if
// user is "user123" and password is "pass123"
if (securityController.credentialsValid(name, password)) {
// TODO authenticate
login = name;
userGroups = new ArrayList<String>();
userGroups.add("admin");
return true;
}
if (name != null &&
name.equals("user123") &&
password != null &&
password.equals("pass123")) {
// We store the username and roles
// fetched from the credentials provider
// to be used later in commit() method.
// For this tutorial we hard coded the
// "admin" role
login = name;
userGroups = new ArrayList<String>();
userGroups.add("admin");
return true;
}
// If credentials are NOT OK we throw a LoginException
throw new LoginException("Authentication failed");
} catch (IOException e) {
throw new LoginException(e.getMessage());
} catch (UnsupportedCallbackException e) {
throw new LoginException(e.getMessage());
}
}
@Override
public boolean commit() throws LoginException {
userPrincipal = new UserPrincipal(login);
subject.getPrincipals().add(userPrincipal);
if (userGroups != null && userGroups.size() > 0) {
for (String groupName : userGroups) {
rolePrincipal = new RolePrincipal(groupName);
subject.getPrincipals().add(rolePrincipal);
}
}
return true;
}
@Override
public boolean abort() throws LoginException {
return false;
}
@Override
public boolean logout() throws LoginException {
subject.getPrincipals().remove(userPrincipal);
subject.getPrincipals().remove(rolePrincipal);
return true;
}
}
</code></pre>
<p>Edit: My run configuration arguments in eclipse for tomcat:</p>
<pre><code>-Dcatalina.base="D:\Dropbox\EclipseWorkspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp7" -Dcatalina.home="D:\Servers\GenTreeUploader_Tomcat7" -Dwtp.deploy="D:\Dropbox\EclipseWorkspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp7\wtpwebapps" -Djava.endorsed.dirs="D:\Servers\GenTreeUploader_Tomcat7\endorsed" -Djava.security.auth.login.config="D:\Dropbox\EclipseWorkspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp7\conf\jaas.config"
</code></pre>
<p>Well? Any ideas?</p> | 16,643,919 | 4 | 2 | null | 2013-05-19 19:53:30.097 UTC | 1 | 2015-07-28 19:47:51.637 UTC | 2013-05-20 10:07:35.057 UTC | null | 1,281,120 | null | 1,281,120 | null | 1 | 19 | java|eclipse|authentication|tomcat|jaas | 70,819 | <p>According to <a href="http://tomcat.apache.org/tomcat-7.0-doc/realm-howto.html#JAASRealm">http://tomcat.apache.org/tomcat-7.0-doc/realm-howto.html#JAASRealm</a></p>
<p>You should set up a login.config file for Java and tell Tomcat where to find it by specifying its location to the JVM, for instance by setting the environment variable:
<code>JAVA_OPTS=$JAVA_OPTS -Djava.security.auth.login.config=$CATALINA_BASE/conf/jaas.config</code></p>
<p><strong>Added</strong></p>
<p>For Windows open <code>startup.bat</code>
Add the following line: <code>set JAVA_OPTS=%JAVA_OPTS% -Djava.security.auth.login.config=%CATALINA_HOME%/conf/jaas.config</code> after <code>okHome</code></p>
<p>e.g.</p>
<pre><code>:okHome
set JAVA_OPTS=%JAVA_OPTS% -Djava.security.auth.login.config=%CATALINA_HOME%/conf/jaas.config
set "EXECUTABLE=%CATALINA_HOME%\bin\catalina.bat"
</code></pre> |
10,083,399 | Change iframe attribute with jquery | <p>I have something like so:</p>
<pre><code> <iframe id="frame" width="200" height="150"
src="http://www.youtube.com/embed/GiZGEFBGgKU?rel=0&
amp&iv_load_policy=3;autoplay=1" frameborder="0" allowfullscreen></iframe>
</code></pre>
<p>And I want to change the width and height using jquery I try:</p>
<pre><code>$("#frame").setAttribute("width", "50");
$("iframe").setAttribute("width", "31");
</code></pre>
<p>None of them work</p> | 10,083,740 | 5 | 0 | null | 2012-04-10 05:14:52.157 UTC | 2 | 2018-04-04 21:25:20.143 UTC | null | null | null | null | 984,734 | null | 1 | 13 | javascript|jquery | 42,590 | <p>As Sarfraz already pointed out, the correct way to set the attribute for a jquery selector object is by using the <code>attr("attrName", "attrVal")</code>. The reason the <code>setAttribute</code> didn't work is something worth explaining, as I've hit my head against this point on more than one occasion:</p>
<p>When you use jquery's selector syntax, it returns an object -- defined in jquery -- which is essentially a list of all of the elements that the selector matched. Whether it matches one element (which should always be the case with an id selector) or more than one, the returned object is the element list, never a single DOM object (eg single element). <code>setAttribute</code> is a method for actual <code>HTMLElement</code> objects.</p>
<p>This is why</p>
<pre><code>$("#frame")[0].setAttribute("width", "200");
</code></pre>
<p>works, but</p>
<pre><code>$("#frame").setAttribute("width", "200");
</code></pre>
<p>does not. The jquery element does not have that method, even though the <code>HTMLElement</code> objects in its list do.</p>
<p>If you wanted to (for whatever reason) use a native <code>HTMLElement</code> method (or a method common to the elements your selector returns, such as inputs, etc), you can use jquery's <code>each()</code> method, like so:</p>
<pre><code> // Set all iframes to width of 250
$("iframe").each(
function(index, elem) {
elem.setAttribute("width","250");
}
);
</code></pre>
<p>The <code>each()</code> method's callback can be passed two optional parameters, the first being the index of the element in the selector list, the second being the actual DOM element, which you can call native DOM methods on.</p>
<p>Like I said, I've gotten really frustrated trying to figure out how to use jquery's selector results with native methods more than once, so I hope this helps clear up not only why <code>setAttribute()</code> doesn't work, but native methods in general, and how to actually get them to work when you can't find the jquery equivalent.</p> |
10,242,766 | atos and dwarfdump won't symbolicate my address | <p>I received a crash report via AirBrake.io that isn't symbolicated. Since the crash report is not in exactly the same format as an Apple crashlog I can't just drop it on XCode as usual, so I took the exact same build from my XCode archive tried to symbolicate it on the commandline. With the following result:</p>
<pre><code>$ atos -o kidsapp.app/kidsapp 0x0002fc4c
0x0002fc4c (in kidsapp)
</code></pre>
<p>I'm absolutely sure I'm using the same build as the crash report is from. So I also tried with dwarfdump:</p>
<pre><code>$ dwarfdump --lookup 0x0002fc4c --arch armv7 kidsapp.app.dSYM
----------------------------------------------------------------------
File: kidsapp.app.dSYM/Contents/Resources/DWARF/kidsapp (armv7)
----------------------------------------------------------------------
Looking up address: 0x000000000002fc4c in .debug_info... not found.
Looking up address: 0x000000000002fc4c in .debug_frame... not found.
</code></pre>
<p>Also no result. Is there anything else besides using the wrong dSYM file that I could do wrong? I know it's the correct one since this is the version referred in the crash report in AirBrake and it's in my XCode archive.</p>
<p>Any ideas/tips are welcome!</p> | 10,280,230 | 6 | 0 | null | 2012-04-20 08:30:16.257 UTC | 24 | 2018-04-11 12:44:22.6 UTC | null | null | null | null | 586,489 | null | 1 | 14 | ios|ipad|dwarf|symbolicate|airbrake | 15,555 | <p>First of all check if the dSYM is really the correct one for that app:</p>
<pre><code>dwarfdump --uuid kidsapp.app/kidsapp
dwarfdump --uuid kidsapp.app.dSYM
</code></pre>
<p>Both should return the same result.</p>
<p>Next check if the dSYM has any valid content</p>
<pre><code>dwarfdump --all kidsapp.app.dSYM
</code></pre>
<p>This should give at least some info, other than <code>not found</code>.</p>
<p>I guess that the dSYM is corrupt. In general you might want to use a crash reporter that gives you a full crash report with all threads and last exception backtrace information. I recommend using something based on PLCrashReporter, e.g. QuincyKit (Open Source SDK + Server + symbolication on your mac) or HockeyApp (Open Source SDK + Paid service + server side symbolication) (Note: I am one of the developers both!)</p> |
9,717,159 | Get iOS iTunes App Store ID of an app itself? | <p>Could an iOS app get the iTunes link of itself? Is there an API for this?</p> | 11,626,157 | 3 | 2 | null | 2012-03-15 09:39:57.06 UTC | 15 | 2020-08-07 10:16:44.03 UTC | 2020-08-07 10:16:44.03 UTC | null | 41,948 | null | 41,948 | null | 1 | 26 | ios|api|app-store|itunes | 48,793 | <p>Here is the answer.</p>
<ol>
<li>The app requests <a href="http://itunes.apple.com/lookup?bundleId=com.clickgamer.AngryBirds" rel="noreferrer">http://itunes.apple.com/lookup?bundleId=com.clickgamer.AngryBirds</a></li>
<li>Find the <code>"version": "2.1.0"</code> and <code>"trackId": 343200656</code> in the JSON response.</li>
</ol>
<p>Warning: This API is undocumented, Apple could change it without notice.</p>
<p>References:</p>
<p>[1] <a href="https://github.com/nicklockwood/iVersion/blob/master/iVersion/iVersion.m#L705" rel="noreferrer">https://github.com/nicklockwood/iVersion/blob/master/iVersion/iVersion.m#L705</a><br>
[2] <a href="https://stackoverflow.com/a/8841636/41948">https://stackoverflow.com/a/8841636/41948</a><br>
[3] <a href="http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsLookup?id=343200656&mt=8" rel="noreferrer">http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsLookup?id=343200656&mt=8</a><br>
[4] <a href="http://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/wsSearch?term=+Angry+Birds&country=US&media=software&entity=softwareDeveloper&limit=6&genreId=&version=2&output=json&callback=jsonp1343116626493" rel="noreferrer">http://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/wsSearch?term=+Angry+Birds&country=US&media=software&entity=softwareDeveloper&limit=6&genreId=&version=2&output=json&callback=jsonp1343116626493</a></p> |
9,959,928 | Double quotes vs single quotes in JavaScript | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/242813/when-to-use-double-or-single-quotes-in-javascript">When to Use Double or Single Quotes in JavaScript</a><br>
<a href="https://stackoverflow.com/questions/8974026/are-there-differences-between-and">Are there differences between ' and "</a> </p>
</blockquote>
<p>I am wondering if there is a difference between using single quotes vs double quotes in JavaScript (JQuery selectors etc.).</p>
<p>Both seem to work just fine, so is there a difference?</p> | 9,959,952 | 4 | 0 | null | 2012-03-31 21:39:31.287 UTC | 5 | 2017-05-01 16:00:52.69 UTC | 2017-05-23 10:31:39.507 UTC | null | -1 | null | 336,423 | null | 1 | 41 | javascript|syntax|semantics | 40,336 | <p>The difference is that you don't need to escape single quotes in double quotes, or double quotes in single quotes. That is the only difference, if you do not count the fact that you must hold the Shift key to type <code>"</code>.</p> |
9,766,608 | zipWith analogue in Python? | <p>What is the analogue of Haskell's <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:zipWith" rel="noreferrer">zipWith</a> function in Python?</p>
<pre><code>zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
</code></pre> | 9,766,647 | 6 | 2 | null | 2012-03-19 07:48:12.057 UTC | 8 | 2017-08-24 20:54:56.943 UTC | 2012-03-19 08:23:44.61 UTC | null | 989,121 | null | 784,533 | null | 1 | 55 | python|haskell | 14,950 | <p>You can create yours, if you wish, but in Python we mostly do </p>
<pre><code>list_c = [ f(a,b) for (a,b) in zip(list_a,list_b) ]
</code></pre>
<p>as Python is not inherently functional. It just happens to support a few convenience idioms. </p> |
9,682,206 | Groovy different results on using equals() and == on a GStringImpl | <p>According to the <a href="http://groovy-lang.org/style-guide.html#_equals_and_code_code" rel="nofollow noreferrer">Groovy docs</a>, the <code>==</code> is just a "clever" <code>equals()</code> as it also takes care of avoiding <code>NullPointerException</code>:</p>
<blockquote>
<p>Java’s <code>==</code> is actually Groovy’s <code>is()</code> method, and Groovy’s <code>==</code> is a clever <code>equals()</code>!</p>
<p>[...]</p>
<p>But to do the usual <code>equals()</code> comparison, you should prefer Groovy’s <code>==</code>, as it also takes care of avoiding <code>NullPointerException</code>, independently of whether the left or right is <code>null</code> or not.</p>
</blockquote>
<p>So, the <code>==</code> and <code>equals()</code> should return the same value if the objects are not null. However, I'm getting unexpected results on executing the following script:</p>
<pre class="lang-groovy prettyprint-override"><code>println "${'test'}" == 'test'
println "${'test'}".equals('test')
</code></pre>
<p>The output that I'm getting is:</p>
<pre class="lang-none prettyprint-override"><code>true
false
</code></pre>
<p>Is this a known bug related to <code>GStringImpl</code> or something that I'm missing?</p> | 9,682,610 | 3 | 0 | null | 2012-03-13 10:24:03.913 UTC | 9 | 2022-03-31 14:18:15.823 UTC | 2021-02-10 21:52:26.477 UTC | null | 1,108,305 | null | 849,775 | null | 1 | 62 | groovy|operator-overloading|equals|gstring | 58,266 | <p>Nice question, the surprising thing about the code above is that</p>
<pre><code>println "${'test'}".equals('test')
</code></pre>
<p>returns <code>false</code>. The other line of code returns the expected result, so let's forget about that.</p>
<h2>Summary</h2>
<pre><code>"${'test'}".equals('test')
</code></pre>
<p>The object that <code>equals</code> is called on is of type <code>GStringImpl</code> whereas <code>'test'</code> is of type <code>String</code>, so they are not considered equal.</p>
<h2>But Why?</h2>
<p>Obviously the <code>GStringImpl</code> implementation of <code>equals</code> could have been written such that when it is passed a <code>String</code> that contain the same characters as <code>this</code>, it returns true. Prima facie, this seems like a reasonable thing to do.</p>
<p>I'm guessing that the reason it wasn't written this way is because it would violate the <code>equals</code> contract, which states that:</p>
<blockquote>
<p>It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. </p>
</blockquote>
<p>The implementation of <code>String.equals(Object other)</code> will always return false when passed a <code>GSStringImpl</code>, so if <code>GStringImpl.equals(Object other)</code> returns true when passed any <code>String</code>, it would be in violation of the symmetric requirement.</p> |
9,909,086 | Multiply TimeSpan in .NET | <p>How do I multiply a TimeSpan object in C#? Assuming the variable <code>duration</code> is a <a href="http://msdn.microsoft.com/en-us/library/system.timespan.aspx" rel="noreferrer">TimeSpan</a>, I would like, for example</p>
<pre><code>duration*5
</code></pre>
<p>But that gives me an error "operator * cannot be applied to types TimeSpan and int". Here's my current workaround</p>
<pre><code>duration+duration+duration+duration+duration
</code></pre>
<p>But this doesn't extend to non-integer multiples, eg. <code>duration * 3.5</code> </p> | 9,909,126 | 9 | 0 | null | 2012-03-28 13:59:53.667 UTC | 6 | 2021-12-22 20:55:51.547 UTC | 2013-01-11 16:36:37.927 UTC | null | 284,795 | null | 284,795 | null | 1 | 95 | c#|.net|date|time|timespan | 29,408 | <p><a href="http://www.blackwasp.co.uk/TimespanMultiplication.aspx">From this article</a></p>
<pre><code>TimeSpan duration = TimeSpan.FromMinutes(1);
duration = TimeSpan.FromTicks(duration.Ticks * 12);
Console.WriteLine(duration);
</code></pre> |
7,821,361 | How to write Pagination logic? | <p>Can anyone provide some idea/logic to write the pagination logic for the search page i am working on?
The information i have is <strong>total number of pages</strong> for that search- <strong>10 records per page</strong> also i am been sent the both the previous and next page number(no problem writing the logic all i need to do i pull that info and populate. I am also getting the info which page i am on. I can only display 10 pages like below</p>
<pre><code><previous 1 |2 |3 | 4| 5 | 6 | 7 | 8 | 9 | 10 next>
</code></pre>
<p>Say if total pages are 15 and when user click next then i need to display like this</p>
<pre><code><previous 2 |3 |4 |5 |6 |7 |8 |9 |10 |11 next>
</code></pre>
<p>At any time i just need to show then 10 pages in the pagination. </p>
<pre><code> #set($start = 1)
#set($end = $Integer.parseInt($searchTO.getPagination().getNumberofPages()))
#set($range = [$start..$end])
#set($iter = 1)
#foreach($i in $range)
#foreach($link in $searchTO.getPagination().getDirectPageLinks())
#if($i == $iter)
#if ($Integer.parseInt($searchTO.getPagination().getPageNumber())==$iter)
<a class="search_current" href="/?_page=SEARCH&_action=SEARCH$link">$i &nbsp|</a>
#else
<a href="/?_page=SEARCH&_action=SEARCH$link">$i &nbsp|</a>
#end
#set($iter = 1)
#break
#else
#set($iter=$iter+1)
#end
#end
#end
</code></pre> | 7,822,000 | 3 | 5 | null | 2011-10-19 12:33:18.18 UTC | 12 | 2017-04-05 04:11:29.07 UTC | 2011-10-19 12:46:19.667 UTC | null | 724,238 | null | 724,238 | null | 1 | 8 | java|pagination|velocity | 71,823 | <p>Here is how I would implement it:
It is generally a good idea to create a Filter class that filters data and contains pagination related information for you. I use something like this:</p>
<pre><code>public abstract class Filter{
/** Member identifier for the current page number */
private int currentPageNo;
/** Member identifier for the current start page number in the page navigation */
private int currentStartPageNo;
/** Member identifier for the current end page number in the page navigation */
private int currentEndPageNo;
/** Member identifier for the number of elements on a page */
private int elementsPerPage;
/** Member identifier for the number of pages you have in the navigation (i.e 2 to 11 or 3 to 12 etc.) */
private int pageNumberInNavigation;
public abstract Query createCountQuery();
public abstract Query createQuery();
public void setCurrentPageNo(){
//Your code here
//Validation, variable setup
}
public Long getAllElementsCount(){
//Now this depends on the presistence framework you use, this code is
//just for guidance and has Hibernate-like syntax
Query query = createCountQuery();
List list = query.list();
return !list.isEmpty() && list.get(0) != null ? query.list().get(0) : 0;
}
public List getElements(){
//Now this depends on the presistence framework you use, this code is
//just for guidance and has Hibernate-like syntax
Query query = createQuery();
int from = ((currentPageNo - 1) * elementsPerPage);
query.setFirstResult(from);
query.setMaxResults(elementsPerPage);
//If you use Hibernate, you don't need to worry for null check since if there are no results then an empty collection is returned
return query.list();
}
public List getAllElements(){
Query query = createQuery();
return query.list();
}
public void refresh(){
//Your code here
}
public List next(){
//Move to the next page if exists
setCurrentPageNo(getCurrentPageNo() + 1);
getElements();
}
public List previoius(){
//Move to the previous page if exists
setCurrentPageNo(getCurrentPageNo() - 1);
getElements();
}
}
</code></pre>
<p>You could have special subclasses of filters (depending on what you want to retrieve) and and each subclass would implement it's <code>createCountQuery()</code> and <code>createQuery()</code>.</p>
<p>You would put then your <code>Filter</code> to the <code>Velocity</code> context and you could retrieve all the information you need from this class.</p>
<p>When you set the current page pf course you update all the other information that you need (i.e. currentStartPageNo, currentEndPageNo).</p>
<p>You could also have a <code>refresh()</code> method to put the filter back to its initial state.</p>
<p>And of course you should keep the instance of the same filter on the session (I mean you web framework like Struts, Turbine etc.) while the user navigates on the search page to which the <code>Filter</code> belongs.</p>
<p>This is just a guideline, an idea, it is not fully written executable code, just an example to get you started in a direction.</p>
<p>I would also recommend you a jQuery plugin called <a href="http://www.trirand.com/blog/">jqGrid</a> that has pagination support (although you have to have a backed to retrieve data) and a lot more cool stuff.
You can use it to display your data in a grid. I use it together with <code>Velocity</code> with no problem. It has a lot of very nice and useful features like filter toolbar, editable cells, data transfer in <code>JSON</code>, <code>XML</code> etc.
Honestly, I do not know if it has pagination like you need (I use it with only one page displayed in the navigation and you can not click on a page just use the next a prev buttons to navigate), but it may have support for that.</p> |
11,648,748 | Mount Android emulator images | <p>I am trying to analyse Android malware on an emulator with Android 2.1. I want to analyze the files permissions and fingerprints after the execution of the suspicious app. I know, I can use the <code>adb shell</code> to get this information, but I think I can't trust the information after the execution of e.g. a rootkit.</p>
<p>I think the only way to prevent rootkits from hiding is by mounting the images directly or?
I have the following files:</p>
<pre><code>ramdisk.img snapshots.img userdata-qemu.img cache.img system.img userdata.img zImage
</code></pre>
<p>How can they be mounted/extracted on Ubuntu (read access is enough)?</p>
<p>With unyaffs I can extract the <code>system.img</code> and <code>userdata.img</code> file. simg2img returns "bad magic" for all files.</p>
<p>Thanks Alex</p>
<p>Edit: <code>userdata-qemu.img</code> works unyaffs2</p> | 12,282,909 | 3 | 0 | null | 2012-07-25 11:31:17.957 UTC | 9 | 2021-03-22 15:07:00.11 UTC | 2021-03-22 14:09:47.527 UTC | null | 340,175 | null | 1,136,474 | null | 1 | 15 | android|image|emulation|mount | 21,730 | <p>You've already answered your own question but I'll expand a bit.
The Android sdk comes with system images, for example:</p>
<pre><code>$ cd android-sdk-linux/system-images/android-15/armeabi-v7a/
$ ls *.img
ramdisk.img system.img userdata.img
$ cd ~/.android/avd/<img name>.avd/
$ ls *.img
cache.img sdcard.img userdata.img userdata-qemu.img
</code></pre>
<p>Though, not all images are of the same type:</p>
<pre><code>$ file *.img
cache.img: VMS Alpha executable
sdcard.img: x86 boot sector, code offset 0x5a, OEM-ID "MSWIN4.1", sectors/cluster 4, Media descriptor 0xf8, sectors 2048000 (volumes > 32 MB) , FAT (32 bit), sectors/FAT 3993, reserved3 0x800000, serial number 0x17de3f04, label: " SDCARD"
userdata.img: VMS Alpha executable
userdata-qemu.img: VMS Alpha executable
</code></pre>
<p>Since <code>sdcard.img</code> contains no extra partitions, it can be mounted directly without an offset parameter (like <code>-o loop,offset=32256</code>):</p>
<pre><code>$ fdisk -l sdcard.img
You must set cylinders.
You can do this from the extra functions menu.
Disk sdcard.img: 0 MB, 0 bytes
255 heads, 63 sectors/track, 0 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0x00000000
Device Boot Start End Blocks Id System
$ sudo mount -o loop sdcard.img /mnt/
</code></pre>
<p>The other image files which are described as <code>VMS Alpha executable</code> are in fact <a href="http://en.wikipedia.org/wiki/YAFFS" rel="noreferrer">yaffs2</a> files. As far as I'm aware they can't be mounted directly but can be extracted using the two utilities <a href="http://code.google.com/p/unyaffs/" rel="noreferrer">unyaffs</a> or <a href="http://code.google.com/p/yaffs2utils/" rel="noreferrer">unyaffs2</a>.</p>
<pre><code>$ mkdir extract
$ cd extract
$ unyaffs ../userdata.img
</code></pre>
<p>or</p>
<pre><code>$ unyaffs2 --yaffs-ecclayout ../userdata.img .
</code></pre>
<p>Note, there's another utility called <code>simg2img</code> which can be found in the android source tree under <code>./android_src/system/extras/ext4_utils/</code> which is used on compressed ext4 img files. However, if wrongly applied to <code>yaffs2</code> images it complains with <code>Bad magic</code>.</p> |
11,487,646 | Intellij Idea does not find my android device | <p>Hi I want to do some test app that uses sound recording, but it doesn't work in the emulator. I need to test it on my phone but every time I change the option to use USB, it never detects my Wildfire S ... which is connected and in USB debugging mode.</p>
<p>It says "No USB Device Found".</p>
<p>Using 11.1.2</p>
<p>Any ideas?</p> | 11,488,139 | 8 | 2 | null | 2012-07-14 21:51:28.713 UTC | 1 | 2020-05-29 14:38:22.593 UTC | null | null | null | null | 966,823 | null | 1 | 17 | android|debugging|intellij-idea|adb | 51,285 | <p>Problem was solved by installing HTC Sync it installed the correct driver and allowed me to detect the device.</p> |
11,979,156 | Mobile Safari back button | <p>The issue I've found is very similar to <a href="https://stackoverflow.com/questions/24046/the-safari-back-button-problem">this question</a>, except that Safari on desktops seems to have resolved the issue. Essentially, the issue is this: when a client is browsing on mobile safari and the page executes a javascript function on <code>pageA.html</code>, then navigate to <code>pageB.html</code>, then press the back button to go back to <code>pageA.html</code>, the javascript function won't run when the client pressed the back button to come back to <code>pageA.html</code>. It will skip the javascript call.</p>
<p>I've tried the solutions mentioned in the link above, but nothing seems to work for mobile Safari. Has anyone else encountered this bug? How did you handle it?</p> | 12,652,160 | 1 | 1 | null | 2012-08-16 00:32:29.697 UTC | 21 | 2020-06-29 12:39:42.343 UTC | 2020-06-29 12:39:42.343 UTC | null | 619,978 | null | 1,124,703 | null | 1 | 37 | javascript|safari | 34,205 | <p>This is caused by <a href="https://developer.mozilla.org/en-US/docs/Using_Firefox_1.5_caching" rel="noreferrer">back-forward cache</a>. It is supposed to save complete state of page when user navigates away. When user navigates back with back button page can be loaded from cache very quickly. This is different from normal cache which only caches HTML code.</p>
<p>When page is loaded for bfcache <code>onload</code> event wont be triggered. Instead you can check the <code>persisted</code> property of the <code>onpageshow</code> event. It is set to false on initial page load. When page is loaded from bfcache it is set to true.</p>
<pre><code>window.onpageshow = function(event) {
if (event.persisted) {
alert("From back / forward cache.");
}
};
</code></pre>
<p>For some reason jQuery does not have this property in the event. You can find it from original event though.</p>
<pre><code>$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
alert("From back / forward cache.");
}
});
</code></pre>
<p>Quick solution to these problem is to reload the page when back button is pressed. This however nullifies any positive effect back / forward cache would give.</p>
<pre><code>window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload()
}
};
</code></pre>
<p>As a sidenote, you can see lot of pages offering using empty <code>onunload</code> handler as solution. This has not worked since iOS5.</p>
<pre><code>$(window).bind("unload", function() { });
</code></pre> |
11,865,195 | Using If/Else on a data frame | <p>I have a data set which looks something like</p>
<pre><code>data<-c(0,1,2,3,4,2,3,1,4,3,2,4,0,1,2,0,2,1,2,0,4)
frame<-as.data.frame(data)
</code></pre>
<p>I now want to create a new variable within this data frame. If the column "data" reports a number of 2 or more, I want it to have "2" in that row, and if there is a 1 or 0 (e.g. the first two observations), I want the new variable to have a "1" for that observation.</p>
<p>I am trying to do this using the following code:</p>
<pre><code>frame$twohouses<- if (any(frame$data>=2)) {frame$twohouses=2} else {frame$twohouses=1}
</code></pre>
<p>However if I run these 3 lines of script, every observation in the column "twohouses" is coded with a 2. However a number of them should be coded with a 1.</p>
<p>So my question: what am I doing wrong with my if else line or script? Or is there an alternative way to do this.</p>
<p>My question is similar to this one:
<a href="https://stackoverflow.com/questions/11275120/using-ifelse-on-factor-in-r">Using ifelse on factor in R</a></p>
<p>but no one has answered that question.</p>
<p>Many thanks in advance!</p> | 11,865,283 | 2 | 1 | null | 2012-08-08 13:07:37.233 UTC | 12 | 2018-07-26 10:42:27.353 UTC | 2017-05-23 12:34:24.807 UTC | null | -1 | null | 1,545,812 | null | 1 | 40 | r | 151,927 | <p>Use <code>ifelse</code>:</p>
<pre><code>frame$twohouses <- ifelse(frame$data>=2, 2, 1)
frame
data twohouses
1 0 1
2 1 1
3 2 2
4 3 2
5 4 2
...
16 0 1
17 2 2
18 1 1
19 2 2
20 0 1
21 4 2
</code></pre>
<hr>
<p>The difference between <code>if</code> and <code>ifelse</code>:</p>
<ul>
<li><code>if</code> is a control flow statement, taking a single logical value as an argument</li>
<li><code>ifelse</code> is a vectorised function, taking vectors as all its arguments.</li>
</ul>
<p>The help page for <code>if</code>, accessible via <code>?"if"</code> will also point you to <code>?ifelse</code></p> |
11,523,918 | Start a Function at Given Time | <p>How can I run a function in <em>Python</em>, at a given time?</p>
<p>For example:</p>
<pre><code>run_it_at(func, '2012-07-17 15:50:00')
</code></pre>
<p>and it will run the function <code>func</code> at 2012-07-17 15:50:00.</p>
<p>I tried the <a href="http://docs.python.org/library/sched.html#scheduler-objects" rel="noreferrer">sched.scheduler</a>, but it didn't start my function.</p>
<pre><code>import time as time_module
scheduler = sched.scheduler(time_module.time, time_module.sleep)
t = time_module.strptime('2012-07-17 15:50:00', '%Y-%m-%d %H:%M:%S')
t = time_module.mktime(t)
scheduler_e = scheduler.enterabs(t, 1, self.update, ())
</code></pre>
<p>What can I do?</p> | 11,524,152 | 9 | 5 | null | 2012-07-17 13:49:25.277 UTC | 29 | 2022-01-29 23:01:27.477 UTC | 2022-01-29 23:01:27.477 UTC | null | 3,750,257 | null | 685,395 | null | 1 | 53 | python|time|scheduler | 115,322 | <p>Reading the docs from <a href="http://docs.python.org/py3k/library/sched.html" rel="noreferrer">http://docs.python.org/py3k/library/sched.html</a>:</p>
<p>Going from that we need to work out a delay (in seconds)...</p>
<pre><code>from datetime import datetime
now = datetime.now()
</code></pre>
<p>Then use <code>datetime.strptime</code> to parse '2012-07-17 15:50:00' (I'll leave the format string to you)</p>
<pre><code># I'm just creating a datetime in 3 hours... (you'd use output from above)
from datetime import timedelta
run_at = now + timedelta(hours=3)
delay = (run_at - now).total_seconds()
</code></pre>
<p>You can then use <code>delay</code> to pass into a <code>threading.Timer</code> instance, eg:</p>
<pre><code>threading.Timer(delay, self.update).start()
</code></pre> |
20,242,841 | How to resolve java net ConnectException Connection refused connect even server is up | <p>I am using Httpurlconnection to send request from my jboss server to my device. The Device has been build up by cgi. </p>
<p>When server sends request from multiple thread at a time to device, some thread got an exception as java.net.ConnectException: Connection refused. but the device is sending response to server in some delay. I have set httpurlconnection timeout as 30 seconds(3000 milliseconds). </p>
<p>But the error has come only when multiple thread sending it at same time.</p>
<p>Does any one know please guide me to resolve the problem.</p>
<pre><code>java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:233)
at sun.net.www.http.HttpClient.New(HttpClient.java:306)
at sun.net.www.http.HttpClient.New(HttpClient.java:323)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:852)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:793)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:718)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1041)
</code></pre> | 20,243,258 | 1 | 3 | null | 2013-11-27 12:42:50.27 UTC | 1 | 2013-11-27 13:23:06.973 UTC | 2013-11-27 12:54:34.09 UTC | null | 2,902,100 | null | 2,902,100 | null | 1 | 2 | java|sockets|httpurlconnection | 39,372 | <p>If a single thread connects fine, <em>every time</em>, but some threads running concurrently get this exception, then this is most likely due to a limited number of connections available. Can you change how many concurrent connections are available on the device? If not, then you can try limiting the number of threads that attempt to make the connection.</p>
<p>EDIT: If you can't modify the "device" application or configure it for debugging, then try to see the exact behavior of the threads that are attempting to connect to it. Use a debugger on the client (which is your jboss server in this case) or log debug info from the threads showing connect and release times to see if the exception <em>always</em> occurs when multiple threads are attempting to connect simultaneously (as opposed to threads finishing the connection before other threads connect or timeout). </p>
<p><strong>If</strong> it turns out that it really is a connection limit causing the issue, you could try creating a singleton connection object that is shared among threads. This will seriously bottle neck the jboss application when multiple threads attempt to connect. If that isn't acceptable, you'll have to come up with a new solution (e.g. multiple devices, write your own app, etc).</p> |
20,292,692 | Installing USB driver for Nexus 4 (with KitKat) on Windows 8 64-bit - "no compatible software driver" | <p>I'm desperately trying to install ADB USB drivers for my Nexus 4, which (as you might know) are required for any form of Android Development. You could also say, that they are the single most necessary tool used for Android programming, right? I have already often set up an Android Development Environment for my old HTC Desire, but I am failing with setting it up for my Nexus 4.</p>
<p>The way I go about it:</p>
<ul>
<li>Running Windows 8 and 8.1 Preview (tried everything on two different machines)</li>
<li>Downloading the Android Development Tools from Google (SDK+ADT+Eclipse+etc.)</li>
<li>Downloading the Google USB Drivers (v8) via Android SDK Manager</li>
<li>In the Device Manager i have an entry "Nexus 4" which I right-click and then I select "Update Driver Software..."</li>
<li>-> Browse my Computer for driver software -> Let me pick a list of device drivers on my computer -> Have Disk... -> Choose Path to Google Drivers -> Dialog occurs:</li>
<li>"The folder you specified doesn't contain a compatible software driver for your device. [...]"</li>
</ul>
<p>I really do not know what the problem is. Some things I already tried include:</p>
<ul>
<li>Doing everything on USB3/USB2 Port</li>
<li>Changing Computer Connection Mode to PTP (instead of MTP)</li>
<li>Doing everything on Win8/Win8.1 Preview</li>
<li>I tried to install the universal ADB Driver: download.clockworkmod.com/test/UniversalAdbDriverSetup6.msi without any significant result</li>
</ul>
<p>I fear that the problem is because of the new driver version (v8) or KitKat, because I can't find any working solutions on the net and KitKat is relatively new, however, does anyone have a solution to this?</p> | 27,651,449 | 2 | 8 | null | 2013-11-29 20:05:06.343 UTC | 1 | 2015-02-17 20:21:05.663 UTC | 2014-12-17 02:28:48.63 UTC | null | 2,581,872 | null | 1,411,171 | null | 1 | 16 | android|windows-8|windows-8.1|android-4.4-kitkat|nexus-4 | 63,882 | <p>Enable Debug-Mode on the device. </p>
<p><strong>Steps to enable debug mode:</strong> </p>
<p>Before you do anything in order to develop on a Nexus 4 (at least in my experience), do the following: </p>
<ul>
<li>Open <strong>Settings</strong> App</li>
<li>Navigate to <strong>About Phone</strong></li>
<li>click <strong>Build number</strong> seven times to active the Developer Mode - Settings main screen->Developer options->enable "USB debugging" </li>
</ul>
<p>In my defense: It doesn't say anywhere, that this is a prequisite for Android development. I knew of this option, but since the last time I set this option on a device is years ago, I just thought to myself "well... I do not want to debug, so this option is irrelevant"</p> |
3,421,469 | How to test scientific software? | <p>I'm convinced that software testing indeed is very important, especially in science. However, over the last 6 years, I never have come across any scientific software project which was under regular tests (and most of them were not even version controlled). </p>
<p>Now I'm wondering how you deal with software tests for scientific codes (numerical computations). </p>
<p>From my point of view, standard unit tests often miss the point, since there is no exact result, so using <code>assert(a == b)</code> might prove a bit difficult due to "normal" numerical errors. </p>
<p>So I'm looking forward to reading your thoughts about this. </p> | 3,421,596 | 4 | 2 | null | 2010-08-06 06:30:06.843 UTC | 22 | 2019-10-04 09:41:17.457 UTC | 2017-10-05 21:52:09.77 UTC | null | 3,924,118 | null | 383,239 | null | 1 | 37 | unit-testing|testing|scientific-computing | 3,800 | <p>I am also in academia and I have written quantum mechanical simulation programs to be executed on our cluster. I made the same observation regarding testing or even version control. I was even worse: in my case I am using a C++ library for my simulations and the code I got from others was pure spaghetti code, no inheritance, not even functions.</p>
<p>I rewrote it and I also implemented some unit testing. You are correct that you have to deal with the numerical precision, which can be different depending on the architecture you are running on. Nevertheless, unit testing is possible, as long as you are taking these numerical rounding errors into account. Your result should not depend on the rounding of the numerical values, otherwise you would have a different problem with the robustness of your algorithm.</p>
<p>So, to conclude, I use unit testing for my scientific programs, and it really makes one more confident about the results, especially with regards to publishing the data in the end.</p> |
3,705,591 | Do I encode ampersands in <a href...>? | <p>I'm writing code that automatically generates HTML, and I want it to encode things properly.</p>
<p>Say I'm generating a link to the following URL:</p>
<pre><code>http://www.google.com/search?rls=en&q=stack+overflow
</code></pre>
<p>I'm assuming that all attribute values should be HTML-encoded. (Please correct me if I'm wrong.) So that means if I'm putting the above URL into an anchor tag, I should encode the ampersand as <code>&amp;</code>, like this:</p>
<pre><code><a href="http://www.google.com/search?rls=en&amp;q=stack+overflow">
</code></pre>
<p>Is that correct?</p> | 3,705,601 | 4 | 4 | null | 2010-09-14 01:36:43.09 UTC | 26 | 2021-11-10 02:41:23.447 UTC | null | null | null | null | 4,321 | null | 1 | 174 | html | 66,128 | <p>Yes, it is. HTML entities are parsed inside HTML attributes, and a stray <code>&</code> would create an ambiguity. That's why you should always write <code>&amp;</code> instead of just <code>&</code> inside <strong>all</strong> HTML attributes.</p>
<p>That said, only <code>&</code> and quotes <em>need</em> to be encoded. If you have special characters like <code>é</code> in your attribute, you don't need to encode those to satisfy the HTML parser.</p>
<p>It used to be the case that URLs needed special treatment with non-ASCII characters, like <code>é</code>. You had to encode those using percent-escapes, and in this case it would give <code>%C3%A9</code>, because they were defined by <a href="http://www.ietf.org/rfc/rfc1738.txt" rel="nofollow noreferrer">RFC 1738</a>. However, RFC 1738 has been superseded by <a href="https://www.rfc-editor.org/rfc/rfc3986" rel="nofollow noreferrer">RFC 3986</a> (URIs, Uniform Resource Identifiers) and <a href="https://www.rfc-editor.org/rfc/rfc3987" rel="nofollow noreferrer">RFC 3987</a> (IRIs, Internationalized Resource Identifiers), on which the <a href="http://url.spec.whatwg.org/" rel="nofollow noreferrer">WhatWG based its work to define how browsers should behave when they see an URL with non-ASCII characters in it since HTML5</a>. It's therefore now safe to include non-ASCII characters in URLs, percent-encoded or not.</p> |
3,557,780 | Add string to char array in C | <p>I have a C array called buf. Here is it's definition:</p>
<p><code>char buf[1024];</code></p>
<p>Now, my current code takes from <code>stdin</code> and uses <code>fgets()</code> to set that array, however I wish to use code to set it instead. Right now the line that sets buf looks like this:</p>
<p><code>fgets(buf, 1024, stdin);</code></p>
<p>Basically, I want to replace stdin, with say... "My String". What's the best way to do this?</p> | 3,557,791 | 5 | 0 | null | 2010-08-24 14:54:17.453 UTC | 4 | 2010-08-24 17:06:24.677 UTC | null | null | null | null | 231,721 | null | 1 | 2 | c|arrays|string|char|fgets | 50,437 | <p>Look for <code>sprintf</code>, for example here: <a href="http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/" rel="noreferrer">Cpp reference</a></p>
<p>Edit:</p>
<pre><code>sprintf(buf, "My string with args %d", (long) my_double_variable);
</code></pre>
<p>Edit 2:</p>
<p>As suggested to avoid overflow (but this one is standard C) you can use <a href="http://www.cppreference.com/wiki/c/io/snprintf" rel="noreferrer">snprintf</a>.</p> |
3,546,186 | TINYINT vs ENUM(0, 1) for boolean values in MySQL | <p>Which one is better, Tinyint with 0 and 1 values or ENUM 0,1 in MyISAM tables and MySQL 5.1?</p> | 3,546,296 | 5 | 1 | null | 2010-08-23 09:19:31.667 UTC | 5 | 2019-12-30 08:30:50.82 UTC | 2011-10-19 03:52:04.163 UTC | null | 135,152 | null | 396,472 | null | 1 | 30 | php|mysql|enums|tinyint | 27,679 | <p>You can use <code>BIT(1)</code> as mentioned in <a href="http://dev.mysql.com/doc/refman/5.1/en/numeric-type-overview.html" rel="noreferrer">mysql 5.1 reference</a>. i will not recommend <code>enum</code> or <code>tinyint(1)</code>
as <code>bit(1)</code> needs only 1 bit for storing boolean value while <code>tinyint(1)</code> needs 8 bits.</p> |
3,348,881 | Offset viewable image in <img> tags the same way as for background-image | <p>Using plain <img> tags is it possible to offset the image in the same way as you can with CSS background-image and background-position?</p>
<p>There are main images on the page and it makes little sense to have separate thumbnails when both will be loaded (thus increasing bandwidth). Some of the images are portrait and some are landscape, however I need to display the thumbnails at a uniform size (and crop off the excess where it fails to meet the desired aspect ratio).</p>
<p>Although this is possible using other tags and background- CSS values the use of plain <img> tags would be preferable.</p> | 57,960,751 | 5 | 0 | null | 2010-07-27 23:50:59.79 UTC | 6 | 2019-09-16 16:11:48.65 UTC | 2010-07-28 00:09:09.92 UTC | null | 30,618 | null | 179,454 | null | 1 | 32 | html|css | 52,565 | <p>This is an old question, but it was the first one that came up when I googled the question, so I thought I would mention the answer that, in my opinion, actually solves the original problem how to emulate <code>background-position</code> attribute. The answer I found is to use CSS attributes <code>object-position</code> and <code>object-fit</code>. For example like this:</p>
<pre><code><img src="logos.png" style="object-fit: none; object-position: -64px 0; width: 32px; height: 32px" />
</code></pre>
<p>This will show the third thumbnail in the first row (assuming the thumbnails are arranged in a regular grid 32 x 32 pixels).</p> |
3,247,173 | Can I see if a timer is still running? | <p>Simple question here that I can't seem to find an answer for: Once a <code>setTimeout</code> is set, is there any way to see if it's still, well, set?</p>
<pre><code>if (!Timer)
{
Timer = setTimeout(DoThis,60000);
}
</code></pre>
<p>From what I can tell, when you <code>clearTimeout</code>, the variable remains at its last value. A <code>console.log</code> I just looked at shows <code>Timer</code> as being '12', no matter if the timeout has been set or cleared. Do I have to null out the variable as well, or use some other variable as a boolean saying, yes, I have set this timer? Surely there's a way to just check to see if the timeout is still running... right? I don't need to know how long is left, just if it's still running.</p> | 3,247,245 | 6 | 0 | null | 2010-07-14 14:32:47.93 UTC | 10 | 2019-09-25 11:27:43.603 UTC | null | null | null | null | 362,520 | null | 1 | 85 | javascript|settimeout | 113,305 | <p>There isn't anyway to interact with the timer except to start it or stop it. I typically null the timer variable in the timeout handler rather than use a flag to indicate that the timer isn't running. There's a nice description on <a href="http://www.w3schools.com/js/js_timing.asp" rel="noreferrer">W3Schools</a> about how the timer works. In their example they use a flag variable.</p>
<p>The value you are seeing is a <a href="http://en.wikipedia.org/wiki/Handle_(computing)" rel="noreferrer"><em>handle</em></a> to the current timer, which is used when you clear (stop) it.</p> |
3,623,739 | Locate Git installation folder on Mac OS X | <p>I'm just curious, Where Git get installed (via DMG) on Mac OS X file system?</p> | 7,089,778 | 11 | 3 | null | 2010-09-02 04:04:16.273 UTC | 35 | 2020-10-09 14:29:01.147 UTC | null | null | null | null | 394,868 | null | 1 | 124 | git|macos | 192,218 | <p>The installer from <a href="http://git-scm.com/" rel="noreferrer">the git homepage</a> installs into <strong>/usr/local/git</strong> by default. See also <a href="https://stackoverflow.com/questions/4725389/how-to-get-started-with-git-on-mac/4725627#4725627" title="this answer">this answer</a>. However, if you install XCode4, it will install a git version in <strong>/usr/bin</strong>. To ensure you can easily upgrade from the website and use the latest git version, edit either your profile information to place <strong>/usr/local/git/bin</strong> before <strong>/usr/bin</strong> in the <strong>$PATH</strong> or edit <strong>/etc/paths</strong> and insert <strong>/usr/local/git/bin</strong> as the first entry (<a href="https://stackoverflow.com/questions/5364340/does-xcode-4-install-git/5365851#5365851">see this answer</a>).</p> |
3,547,388 | PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators | <p>When I send an email with the PHP Swift mailer to this server: smtp.exchange.example.com like this:</p>
<pre><code>// Load transport
$this->transport =
Swift_SmtpTransport::newInstance(
self::$config->hostname,
self::$config->port
)
->setUsername(self::$config->username)
->setPassword(self::$config->password)
;
// Load mailer
$this->mailer = Swift_Mailer::newInstance($this->transport);
// Initialize message
$this->message = Swift_Message::newInstance();
// From
$this->message->setFrom(self::$config->from);
// Set message etc. ...
// Send
$this->mailer->send($this->message);
</code></pre>
<p>I get a strange error back:</p>
<blockquote>
<p>Failed to authenticate on SMTP server with username "[email protected]" using 2 possible authenticators</p>
</blockquote>
<p>I know for sure that the login-info is correct.</p> | 3,565,698 | 13 | 1 | null | 2010-08-23 12:14:06.703 UTC | 7 | 2021-06-09 13:27:58.213 UTC | 2013-12-27 16:10:07.707 UTC | null | 367,456 | null | 219,434 | null | 1 | 25 | php|authentication|smtp|swiftmailer | 113,663 | <p>Strange enough sending emails works again. We did not change anything and the host say they did not either. We think a server restarts or so. It is strange :S</p> |
3,755,136 | Pythonic way to check if a list is sorted or not | <p>Is there a pythonic way to check if a list is already sorted in <code>ASC</code> or <code>DESC</code></p>
<pre><code>listtimestamps = [1, 2, 3, 5, 6, 7]
</code></pre>
<p>something like <code>isttimestamps.isSorted()</code> that returns <code>True</code> or <code>False</code>.</p>
<p>I want to input a list of timestamps for some messages and check if the the transactions appeared in the correct order.</p> | 3,755,251 | 27 | 0 | null | 2010-09-20 20:15:14.093 UTC | 40 | 2022-07-17 08:15:39.19 UTC | 2017-01-21 12:44:58.713 UTC | null | 3,924,118 | null | 225,260 | null | 1 | 181 | python|algorithm|list|sorting | 157,380 | <p>Here is a one liner:</p>
<pre><code>all(l[i] <= l[i+1] for i in range(len(l) - 1))
</code></pre>
<p>If using Python 2, use <code>xrange</code> instead of <code>range</code>.</p>
<p>For <code>reverse=True</code>, use <code>>=</code> instead of <code><=</code>.</p> |
7,865,654 | Printing an array of characters | <p>I have an array of characters declared as:</p>
<pre><code>char *array[size];
</code></pre>
<p>When I perform a</p>
<pre><code>printf("%s", array);
</code></pre>
<p>it gives me some garbage characters, why it is so?</p>
<p><a href="http://www.cplusplus.com/reference/clibrary/cstdio/printf/" rel="noreferrer">http://www.cplusplus.com/reference/clibrary/cstdio/printf/</a></p>
<p>This url indicates printf takes in the format of: `int printf ( const char * format, ... );</p>
<pre><code>#include <stdio.h>
#include <string.h>
#define size 20
#define buff 100
char line[buff];
int main ()
{
char *array[100];
char *sep = " \t\n";
fgets(line, buff, stdin);
int i;
array[0] = strtok(line, sep);
for (i = 1; i < size; i++) {
array[i] = strtok(NULL, sep);
if (array[i] == NULL)
break;
}
return 0;
}
</code></pre> | 7,865,664 | 4 | 1 | null | 2011-10-23 10:43:24.807 UTC | null | 2022-05-11 14:59:01.167 UTC | 2022-05-11 14:59:01.167 UTC | null | 5,784,757 | null | 247,814 | null | 1 | 6 | c|c-strings | 60,193 | <p>Your array is not initialized, and also you have an array of pointers, instead of an array of char's. It should be <code>char* array = (char*)malloc(sizeof(char)*size);</code>, if you want an array of char's. Now you have a pointer to the first element of the array.</p> |
8,078,892 | Stop saving photos using Android native camera | <p>I am using native Android camera and save file to my application data folder (/mnt/sdcard/Android/data/com.company.app/files/Pictures/). At the same time anther copy of photo is saved to DCIM folder. </p>
<p>This is my code:</p>
<pre><code>Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String formattedImageName = getDateString() + ".jpg";
File image_file = new File(this.getExternalFilesDir(Environment.DIRECTORY_PICTURES), formattedImageName);
Uri imageUri = Uri.fromFile(image_file);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(intent, REQUEST_FROM_CAMERA);
</code></pre>
<p>How can I prevent saving additional copy of image to DCIM folder?</p>
<p>Many Thanks</p> | 8,079,078 | 5 | 1 | null | 2011-11-10 11:36:28.113 UTC | 12 | 2018-08-08 16:21:56.637 UTC | 2011-11-10 14:24:48.013 UTC | null | 776,234 | null | 776,234 | null | 1 | 13 | android|native|android-camera|android-sdcard|android-camera-intent | 16,398 | <p>check this code.. </p>
<pre><code>private void FillPhotoList() {
// initialize the list!
GalleryList.clear();
String[] projection = { MediaStore.Images.ImageColumns.DISPLAY_NAME };
for(int i=0;i<projection.length;i++)
Log.i("InfoLog","projection "+projection[0].toString());
// intialize the Uri and the Cursor, and the current expected size.
Cursor c = null;
Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Log.i("InfoLog","FillPhoto Uri u "+u.toString());
// Query the Uri to get the data path. Only if the Uri is valid.
if (u != null)
{
c = managedQuery(u, projection, null, null, null);
}
// If we found the cursor and found a record in it (we also have the id).
if ((c != null) && (c.moveToFirst()))
{
do
{
// Loop each and add to the list.
GalleryList.add(c.getString(0)); // adding all the images sotred in the mobile phone(Internal and SD card)
}
while (c.moveToNext());
}
Log.i(INFOLOG,"gallery size "+ GalleryList.size());
}
</code></pre>
<p><strong>and this is where the method is doing all magic</strong></p>
<pre><code> /** Method will check all the photo is the gallery and delete last captured and move it to the required folder.
*/
public void movingCapturedImageFromDCIMtoMerchandising()
{
// This is ##### ridiculous. Some versions of Android save
// to the MediaStore as well. Not sure why! We don't know what
// name Android will give either, so we get to search for this
// manually and remove it.
String[] projection = { MediaStore.Images.ImageColumns.SIZE,
MediaStore.Images.ImageColumns.DISPLAY_NAME,
MediaStore.Images.ImageColumns.DATA,
BaseColumns._ID,};
// intialize the Uri and the Cursor, and the current expected size.
for(int i=0;i<projection.length;i++)
Log.i("InfoLog","on activityresult projection "+projection[i]);
//+" "+projection[1]+" "+projection[2]+" "+projection[3] this will be needed if u remove the for loop
Cursor c = null;
Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Log.i("InfoLog","on activityresult Uri u "+u.toString());
if (CurrentFile != null)
{
// Query the Uri to get the data path. Only if the Uri is valid,
// and we had a valid size to be searching for.
if ((u != null) && (CurrentFile.length() > 0))
{
//****u is the place from data will come and projection is the specified data what we want
c = managedQuery(u, projection, null, null, null);
}
// If we found the cursor and found a record in it (we also have the size).
if ((c != null) && (c.moveToFirst()))
{
do
{
// Check each area in the gallery we built before.
boolean bFound = false;
for (String sGallery : GalleryList)
{
if (sGallery.equalsIgnoreCase(c.getString(1)))
{
bFound = true;
Log.i("InfoLog","c.getString(1) "+c.getString(1));
break;
}
}
// To here we looped the full gallery.
if (!bFound) //the file which is newly created and it has to be deleted from the gallery
{
// This is the NEW image. If the size is bigger, copy it.
// Then delete it!
File f = new File(c.getString(2));
// Ensure it's there, check size, and delete!
if ((f.exists()) && (CurrentFile.length() < c.getLong(0)) && (CurrentFile.delete()))
{
// Finally we can stop the copy.
try
{
CurrentFile.createNewFile();
FileChannel source = null;
FileChannel destination = null;
try
{
source = new FileInputStream(f).getChannel();
destination = new FileOutputStream(CurrentFile).getChannel();
destination.transferFrom(source, 0, source.size());
}
finally
{
if (source != null)
{
source.close();
}
if (destination != null)
{
destination.close();
}
}
}
catch (IOException e)
{
// Could not copy the file over.
ToastMaker.makeToast(this, "Error Occured", 0);
}
}
//****deleting the file which is in the gallery
Log.i(INFOLOG,"imagePreORNext1 "+imagePreORNext);
Handler handler = new Handler();
//handler.postDelayed(runnable,300);
Log.i(INFOLOG,"imagePreORNext2 "+imagePreORNext);
ContentResolver cr = getContentResolver();
cr.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, BaseColumns._ID + "=" + c.getString(3), null);
break;
}
}
while (c.moveToNext());
}
}
}
</code></pre> |
8,186,965 | What do numbers using 0x notation mean? | <p>What does a <code>0x</code> prefix on a number mean?</p>
<pre><code>const int shared_segment_size = 0x6400;
</code></pre>
<p>It's from a C program. I can't recall what it amounts to and particularly what the letter <code>x</code> means.</p> | 8,186,974 | 5 | 3 | null | 2011-11-18 18:09:33.89 UTC | 44 | 2020-05-16 21:35:11.697 UTC | 2019-01-16 07:50:45.86 UTC | null | 1,364,007 | null | 761,330 | null | 1 | 154 | c|integer|hex|notation | 160,294 | <p>Literals that start with <code>0x</code> are hexadecimal integers. (base 16)</p>
<p>The number <code>0x6400</code> is <code>25600</code>.</p>
<pre><code>6 * 16^3 + 4 * 16^2 = 25600
</code></pre>
<p>For an example including letters (also used in hexadecimal notation where A = 10, B = 11 ... F = 15)</p>
<p>The number <code>0x6BF0</code> is <code>27632</code>.</p>
<pre><code>6 * 16^3 + 11 * 16^2 + 15 * 16^1 = 27632
24576 + 2816 + 240 = 27632
</code></pre> |
7,713,274 | Java Immutable Collections | <p>From <a href="http://download.oracle.com/javase/6/docs/technotes/guides/collections/overview.html" rel="noreferrer">Java 1.6 Collection Framework documentation</a>:</p>
<blockquote>
<p>Collections that do not support any modification operations (such as <code>add</code>, <code>remove</code> and <code>clear</code>) are referred to as <em>unmodifiable</em>. [...] Collections that additionally guarantee that no change in the Collection object will ever be visible are referred to as <em>immutable</em>.</p>
</blockquote>
<p>The second criteria confuses me a bit. Given the first collection is unmodifiable, and assuming that the original collection reference has been disposed away, what are the changes that are referred to in the second line? Is it referring to the changes in the elements held in the collection ie the state of the elements? </p>
<p>Second question:<br>
For a collection to be immutable, how does one go about providing the additional guarentees specified? If the state of an element in the collection is updated by a thread, is it sufficient for immutability that those updates in the state are not visible on the thread holding the immutable collection?</p>
<p><strong>For a collection to be immutable, how does one go about providing the additional guarantees specified?</strong></p> | 7,713,332 | 7 | 1 | null | 2011-10-10 13:12:41.683 UTC | 42 | 2021-09-15 10:07:26.49 UTC | 2020-03-16 06:37:44.767 UTC | null | 757,695 | null | 311,455 | null | 1 | 126 | java|collections|immutability | 191,658 | <p>Unmodifiable collections are usually read-only views (wrappers) of other collections. You can't add, remove or clear them, but the underlying collection can change.</p>
<p>Immutable collections can't be changed at all - they don't wrap another collection - they have their own elements.</p>
<p>Here's a quote from guava's <a href="https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/ImmutableList.html" rel="noreferrer"><code>ImmutableList</code></a></p>
<blockquote>
<p>Unlike <code>Collections.unmodifiableList(java.util.List<? extends T>)</code>, which is a view of a separate collection that can still change, an instance of <code>ImmutableList</code> contains its own private data and will never change. </p>
</blockquote>
<p>So, basically, in order to get an immutable collection out of a mutable one, you have to copy its elements to the new collection, and disallow all operations.</p> |
7,921,840 | OS X Cocoa Auto Layout hidden elements | <p>I am trying to use the new <a href="http://developer.apple.com/library/mac/documentation/UserExperience/Conceptual/AutolayoutPG/Articles/Introduction.html" rel="noreferrer">Auto Layout</a> in Lion because it seems quite nice. But I can not find good information about how to do things. For example:</p>
<p>I have two labels:</p>
<pre><code>+----------------+
| +------------+ |
| + label 1 | |
| +------------+ |
| |
| +------------+ |
| | label 2 | |
| +------------+ |
+----------------+
</code></pre>
<p>but the first label gets not always populated with content, sometimes there ist just no content for it. What I would like to do is to automatically show the label 2 where label 1 would be when it would have content.</p>
<pre><code>+----------------+
| +------------+ |
| + label 2 | |
| +------------+ |
| |
| |
| |
| |
+----------------+
</code></pre>
<p>What constrains would I have to add so it works automatically with autolayout? I understand that I could just code everything, but I have about 30 such labels and images and buttons of different styles and shapes which are all optional and I don't want to add hundrets of lines of code when it could work automatically quite nice too.</p>
<p>If it does not work then I will just use a WebView and do it with HTML and CSS.</p> | 9,429,379 | 8 | 2 | null | 2011-10-27 20:19:05.377 UTC | 10 | 2018-07-17 04:20:22.447 UTC | null | null | null | null | 63,779 | null | 1 | 29 | macos|cocoa|osx-lion | 7,537 | <p>I don't think you could do it that way. If you made the layout for label 2 be based on a distance constraint from label 1, even if you made label 1 auto-collapse to zero height when it has no content, label 2 is still going to be that distance down, ie in:</p>
<pre><code>+----------------+
| +------------+ |
| + label 1 | |
| +------------+ |
| ^ |
| ^ !
| +------------+ |
| | label 2 | |
| +------------+ |
+----------------+
</code></pre>
<p>Where ^ is the autolayout distance constraint - If Label 1 knows how to become zero height when it's string is empty, you're still going to get:</p>
<pre><code>+----------------+
| +------------+ |
| ^ |
| ^ !
| +------------+ |
| | label 2 | |
| +------------+ |
+----------------+
</code></pre>
<p><em>Maybe</em> it is possible by creating your NSLayoutConstraint manually. You could make the second attribute be the height of label 1, make the constant zero, and then carefully work out what the multiplier would be to make the distance be what you want based on a multiple of the non-zero label height.</p>
<p>But having done all this, you've now coded an NSLabel subclass that auto-sizes, created a constraint object manually instead of via the visual language, and bent NSLayoutConstraint beyond its will.</p>
<p>I think you're better off just changing the frame of label 2 if label 1's string is blank!</p> |
4,132,044 | Name database design notation you prefer and why? | <p>Which notation<strike>, methodology </strike> and tools for database designing, modeling, diagraming you prefer and why?
Which notation, standards<strike>, methodology</strike> are the most broadly used and covered by different vendors?</p>
<p>Which are standard and which are not? i.e. which are to stick with and which to avoid?</p>
<p>And why do you prefer IDEF1X? Is not it more comfortable to stick with tools, notations built-in into used client tools of RDBMS?</p>
<h2>Update</h2>
<p>I just read <a href="https://stackoverflow.com/questions/976185/what-are-some-of-your-most-useful-database-standards">What are some of your most useful database standards?</a> I am quite surprised - dozen of answers there and absolutely no names or references, only lengthy descriptions. Are all database developers amateurs using custom-made terminology and conventions?</p>
<p>What I asked for was names (possibly references) not descriptions.<br />
Notations, for example, <a href="http://www.agiledata.org/essays/dataModeling101.html#Notations" rel="nofollow noreferrer">UML, IDEF1X. Barker, Information Engineering</a>.</p>
<p>Well, I am mostly SQL Server dev and, as @dportas mentioned, I see some notation in diagrams in SSMS and msdn docs, books, articles.</p> | 4,140,309 | 3 | 5 | null | 2010-11-09 09:16:49.827 UTC | 13 | 2021-08-18 22:56:37.847 UTC | 2021-08-15 22:59:07.763 UTC | null | 472,495 | null | 200,449 | null | 1 | 10 | sql|database|language-agnostic|database-design|standards | 5,448 | <h2>Extended 11 Dec 10</h2>
<p><strong>What does the question mean ?</strong></p>
<p>Before answering the "notation" question, which is the small visible issue on the surface, we need to understand the issues that underpin it, which lead to the surface issues. Otherwise the relevance to the question is reduced to personal preferences; what some product or other provides, whether it is free, etc.</p>
<h2>Standards</h2>
<p>I assume that the reader has no argument that bridges built for the public out of the public purse (as opposed to hobby bridges built on private land for personal use) need to have standards, in order to ensure that they do not fall over; that they can carry the declared traffic, and that people will not die while using them. The intended standards are first presented by highly acknowledged and recognised engineering experts, and heavily practised and tested by their peers, eventually attaining the status of a Standard, and being declared as such by government standards bodies. The authorities then simply identify the standards that all suppliers must conform to, in order to supply bridges to the government.</p>
<p>It is a waste of time to engage is discussion with non-compliant engineering companies, as what or why their sub-standard offering is worthy of evaluation. Or to look at diagrams that have specific information (demanded by the Standard) missing from them. Or to talk to companies presenting themselves as bridge builders, but who have no civil engineers on the payroll.</p>
<p><strong>Standards are Normalised</strong></p>
<p>Another important aspect of Standards, is that there is no repetition. The bridge building standard only has to refer to the electrical standard for all wiring on the bridge, it does not repeat the content. Standards are Normalised. This allows each Standard to progress and change (eg. as appropriate, due to new building materials becoming available), without affecting other standards or their compliance.</p>
<p>Likewise, Standards do not compete. If one complies with the bridge building standard, there is no danger that one has broken the communications standard.</p>
<p><strong>Standards relate to Higher Principles</strong></p>
<p>Standards are thus the higher principles that every supplier who genuinely supplies quality and performance, will eagerly comply with. And the others will range from reluctant compliance all the way through to ignorance that an applicable standard exists.</p>
<p><strong>Standards are <em>Not</em> a Notation</strong></p>
<p>Third, the Standard is not merely a set of symbols and notations that the diagram must comply with. The unqualified and inexperienced bridge builders may say it is, because of their low level of understanding of the entire set of knowledge required to build faultless bridges, but no. The Standard is always a methodology or set of explicit steps, which are prescribed for the process, which if adhered to, produce the decisions that need to be made at each step, in a progression, so that each decision can be based on previous decisions that have been confirmed, and that can be relied upon. A simple diagram progresses through prescribed standard-compliant stages or phases, with complexity and notations being progressively added, such that the final diagram is compliant.</p>
<p><strong>Standards are Complete</strong></p>
<p>The fourth issue has to do with ensuring that the information conveyed in a diagram is complete and unambiguous. The Standard ensures that the information required is complete. The exercise of the methodology means that ambiguities have been formally identified and resolved. Sub-standard diagrams do not include that requirement of essential Standard information, they are incomplete and contain ambiguities.</p>
<p><strong>Standards are Easy</strong></p>
<p>In addition to the confidence of achieving a certain level of quality, it is actually easier and faster to go through the standard methodology. It is absurd for the non-complaint companies to retro-fit their diagrams by merely supplying standard notation to them. The absence of the prescribed process is visible to any standard-aware person, and the diagram will conflicted (the components s lacking integration).</p>
<p>Responsible, aware customers (government departments, aircraft manufacturers ... companies that expect to be around in the next decade) have reasonable expectations that the software it purchases from suppliers will be of a certain quality; easy to enhance and extend; perform well; will integrate easily with other software; etc.</p>
<p><strong>Lack of Standards in IT</strong></p>
<p>The problem with the IT industry is, unlike the car manufacturing or bridge building industries, since it has exploded in the last 30 years, we have been flooded with providers who are:</p>
<ul>
<li>not educated in IT (do not know the formal steps required for the project)</li>
<li>not qualified in IT (have no idea re what is right and wrong)</li>
<li>not experienced in IT (they are experienced in what they know)</li>
<li>unaware of Standards</li>
<li>work in isolation from their qualified peers</li>
<li>work in the comfort and ease, the isolation, of a single vendor's "products"</li>
<li>have false confidence based on success in isolation</li>
<li>Unskilled and Unaware of It</li>
</ul>
<p>This has been the subject of much research and <a href="http://www.google.co.nz/search?hl=en&client=safari&rls=en&q=unskilled+and+unaware+kruger+dunning&aq=f&aqi=&aql=&oq=&gs_rfai=" rel="nofollow noreferrer">publications</a>, it is not merely my professional opinion, the credit goes to the academics who did the hard work to sift through and identify exactly what the specific issues are.</p>
<p>So in terms of the whole population of IT providers, IT companies as well as IT employees in non-IT companies, the awareness of quality, of the standards required to provide quality, and their importance, is much lower than it was 30 years ago. It is a 'build and forget' mentality; if it doesn't work, throw it out and build another one. But for the big end of town, the responsible aware customers, that is not acceptable.</p>
<p><strong>Standards are Not Single-Vendor</strong></p>
<p>By definition, Standards are arrived at by multiple vendors, at the international level.</p>
<p>One huge problem in the industry is, in spite of having good vendors who supply good tools for real modelling (the resulting diagrams which comply with Standards), we also have vendors who supply a full range of absurd pictures and non-compliant diagrams. This allows IT people to produce good-looking but completely meaningless diagrams. The point is, these horrible little tools actually give people confidence, that they have built a good bridge, a good database. First they create a bunch of spreadsheets, which they load into a container called a "database" and the software helps them think that they now have a "database"; then they use a tool and reverse-engineer the "database" to produce a "data model". It gives them false confidence; they are unaware that they have a funny picture of a bucket of fish, and they feel offended if anyone points that out. Stick with the tools that are standard-compliant by declaration and certification, and toss those that aren't.</p>
<p>The single-vendor non-standard tools may give one comfort and ease, and a false sense of confidence, in isolation. But they cannot be used if one wants to achieve diagrams that convey all required info; confidence that is gained by acceptance of qualified peers; quality that is derived from a prescribed set of steps; confidence that one does not have to keep on reworking the model.</p>
<p><strong>Conventions are Not Standards</strong></p>
<p>And before anyone points out the the horrible tools are "de facto standards", no they aren't, they are common conventions, with no reference to Standards, and we should not confuse the two by using the word "standard" in reference to them. The way one gets out of bed and makes coffee is a convention, possibly very common, but it is not a "standard". Your common vendor, in their commercial interest, may have commercialised you into believing that there is only one "standard" coffee machine and one "standard" coffee bean, but that bears no relation to the Standards to which the coffee machine manufacturer must comply, or the Standard of coffee bean imported into the country.</p>
<p>There is the mis-quotation that MS is infamous for, comparing the progress of car industry to the "progress" of Microsoft, which the car industry responded to publicly, with justified indignation, and wiped the grin off Bill Gate's face. Sun Microsystems also responded, famously, but I doubt that is known in MS circles. Note that MS credibility is gained by sheer volume: the number of internet sites providing and exchanging ever-changing "information" among MS devotees. They are isolated from genuine qualifications and Standards, and falsely believe that single-vendor conventions, and partial performance, using nice-looking pictures, actually comprise "software".</p>
<p><strong>Standards are Not Expensive</strong></p>
<p>That does not mean you have to buy expensive tools. For small projects, it is quite acceptable to draw diagrams using simple drawing tools, because the compliance-to-standards is in the cranium, in the prescribed methodology, not in the tool, and therefore it is possible for a qualified, standards-aware person to produce standard-compliant drawings (for small projects) with any almost tool. And note that those horrible tools which misrepresent themselves do not provide the standard notation; the vast majority of "data models" and "entity relation diagrams" out there, are grossly sub-standard.</p>
<p><strong>Standards re Relational Databases</strong></p>
<p>Standards or precise definitions or specific guidelines, for the following have existed for over 30 years. In progressive order, each containing the previous:</p>
<ol>
<li><p>Normalisation (for any Database)<br />
(a Standard is not required, it is an engineering principle; common across many disciplines; a simple process for those qualified; and absence of it is easily identified.)</p>
</li>
<li><p>Relational Databases<br />
The Relational Model: E F Codd & C J Date</p>
</li>
<li><p>The famous Twelve Rules of Relational Compliance<br />
E F Codd</p>
</li>
<li><p>Relational Data Modelling<br />
<a href="http://www.idef.com/IDEF1x.htm" rel="nofollow noreferrer"><strong>IDEF1X</strong></a>; 1980's; NIST <strong>Standard</strong> FIPS 184 of 1993</p>
</li>
</ol>
<p>There are many suppliers who have practised these methodologies, as prescribed, thereby conforming to the Standards, for up to 30 years.</p>
<ul>
<li><p>Note, there is only one Relational Data Modelling Standard, there is no conflict.</p>
</li>
<li><p>Note, the notation is just what you see on the surface, the result, however it does identify that <em>other</em> notations have info missing from them, and the underlying methodology was not followed.</p>
</li>
<li><p>Note well, that Normalisation pre-dated the Relational Model, and was taken as given; that is why the RM does not have specific references to Normalisation as a principle, and only identifies the Normal Forms, in terms of the requirement for Relational Databases.</p>
</li>
</ul>
<p>If you are genuinely qualified as a Relational Database Modeller, you will be intimately familiar with the first three; if you are a standard-compliant Relational Database Modeller, you will be intimately familiar with the fourth. Again, you cannot reasonably expect to comply with the Standard merely by learning the <a href="http://www.softwaregems.com.au/Documents/Documentary%20Examples/IDEF1X%20Notation.pdf" rel="nofollow noreferrer"><strong>IDEF1X Notation</strong></a>, you need to actually learn and practise the methodology, but learning the Notation may be a reasonable introduction.</p>
<p><strong>[Compliance to] Standard is Demanded [by Some]</strong></p>
<p>There are aware, responsible customers, who demand compliance with these Standards.</p>
<p>And then there is the rest of field, both the unaware customers and the unaware suppliers, and everything in-between.</p>
<p><strong>Which Notation ?</strong></p>
<p>For most standards-aware practitioners, there is no need to discuss "which notation to use", given that there is only one Standard. Why would I draw a diagram (using either an expensive tool in a large project, or a simple drawing tool to answer a question on Stack Overflow), using some other notation when <em>there is no other standard</em> ? Why would I convey less than the Standard information, when I can convey the Standard info just as easily ? Why would I avoid using the Standard, when I know that using the Standard provides the formal confidence that the Data Model is correct, and will stand up to scrutiny (as opposed to the imagined confidence that is punctured by most cursory questioning) ?</p>
<p>If, and when, some qualified, recognised organisation comes up with a new methodology (and believe me, they do, all the time), we look into it. If and when the methodology achieves academic peer recognition and acknowledgement, we will take it seriously, try it out, become adept with it. If and when it is declared a Standard by the international standards bodies (as opposed to single vendor), we will provide it. Until then, we provide the full compliance to Standards that <em>do</em> exist.</p>
<p><strong>Future Notations & Conventions</strong></p>
<p>The couple of hundred single-vendor offerings in the last 20 years were not worth the time spent in investigation. Therefore single-vendor conventions, be they labelled "standards" or not, are not worth the time spent in investigation. In fact, since the Standard exists, and pre-dated the advent of the single vendor, any single-vendor offering would be an implicit declaration that they <em><strong>cannot comply with the Standard</strong></em>, and they are offering an anti-standard as a substitution.</p>
<p><strong>Responses to Comments</strong></p>
<ol>
<li><p>The easiest way to refute an amateur's allegation that some rubbish is a "standard" is to ask for its ISO/ANSI/IEC/NIST/etc publication data. As per (4) above IDEF1X is a published Standard, easy to look up.</p>
</li>
<li><p>MS is famous for publishing anti-standards, and calling them "standards". The correct term is "convention". Wikipedia might call some MS notation a standard this week, but I've already noted that Wikipedia is not a reliable source. Remember, a single-vendor offering is, by definition, not a standard.</p>
</li>
<li><p><em>IDEF1X is also a business process modelling standard</em></p>
</li>
</ol>
<p>Not quite. The <a href="http://www.idef.com/IDEF1x.htm" rel="nofollow noreferrer"><strong>IDEF1X</strong></a> link will take you to the organisation that is most responsible for publicising it and educating people about it. If you check the tabs on that page, you will find several standards. One of the great powers (beauties?) of Standards is that they are integrated:</p>
<ul>
<li><strong>IDEF</strong> stands for <strong>I</strong> ntegrated <strong>Def</strong> inition
<ul>
<li><strong>0</strong> is for Function Modelling</li>
<li><strong>1</strong> is for Information Modelling
- <strong>X</strong> is for Relational Database Modelling</li>
</ul>
</li>
<li>they are all Standards published by NIST<br />
.<br />
I state that in my <a href="http://www.softwaregems.com.au/Documents/Documentary%20Examples/IDEF1X%20Notation.pdf" rel="nofollow noreferrer"><strong>IDEF1X Notation</strong></a> document as well.<br />
.</li>
</ul>
<h2>11 Dec 10</h2>
<ol start="4">
<li><em>What is your attitude to design databases by UML notation (diagram)? The rationale is that it is broadly (and ubiquitously) known and to minimize the number of notations to know for this and that purposes</em></li>
</ol>
<p>First, I would ask, show me a UML "Relational Data Model" that has anywhere near the exposition of detail and subtlety of an IDEF1X model, and then we have something to discuss. Until then, it is idle speculation, pub talk by non-relational people, about what they do not know, from a framework of what they do know.</p>
<p>But I won't avoid the question.</p>
<p>Second, there is a big problem, with horrendous consequences, when people have a fixed mindset about an area of knowledge (Good Thing), but then they approach every other area that they do not know, with the same mindset, unwilling to learn the specialised skills. Those poor people have not read about <a href="http://www.abraham-maslow.com/m_motivation/Maslows_Hammer.asp" rel="nofollow noreferrer"><strong>Maslow's Hammer</strong></a>. The OO types are the biggest offenders. If I have answered this question once, I have answered it ten times, and I have only been here 3 weeks. They ask, as if they were the first person to find this problem, "how do I persist my object classes into a database", and they treat the database (forget Relational) like it is a rubbish bin.</p>
<p>Scott Ambler and Martin Fowler have a lot to answer for when they meet their creator. Complete idiots, except for the income. First they write books on how to model objects the wrong way. Then they turn around (wait for it) and write books about how to fix the problem that they created. Sinful. And this isn't just my opinion, many other real industry leaders (as opposed to published idiots) make similar comments, they are famously written up in "Laugh or Cry" pages. Imagine "refactoring" a database. Only someone who has never read anything about databases would do that. A whole textbook on how to do that. Written by fools who have never seen a real database.</p>
<p>Any serious, experienced modeller knows that if you design (model) the database correctly, it <strong>never needs refactoring</strong>.</p>
<p>The only "databases" that need refactoring are those created by people who treat the db like trash, after reading said "books", and they have explicit steps, on how to keep trashing it, over and over again. You wait, next year they will have "multifactoring".</p>
<p>What's the point ? They never treated the database with respect; never learned about it; how to approach data transfers; how to model it. They just "modelled" it with a Hammer. To someone like me, who fixes these problems in a way that they never come back, "How do I model my multi-level objects classes" tells me immediately they are so clueless, they are "persisting" their Object models into the db, and have not even read enough to understand that the accurate question is "How do I model my Subtypes".</p>
<p>These are the issues on the surface. The flaws are fundamental and deeper, and affect everything they do re the database. Don't believe me, wait just a small amount of time after the "app" goes into production, and it hits the famous wall. They hit it so often, they even have an OO name for it: Object Relational Impedance Mismatch. Very scientific sounding name for plain stupidity. It hasn't occurred to them that if they designed the Relational database as a Relational database, and the OO app as an OO app, with a nice defined boundary, a transport layer between them, there would never be "Object Relational Impedance Mismatch".</p>
<p>The app (any language) and the db is like a good marriage. Each is completely different, they have their own needs, and they need each other. When they work together, it is a marriage made in heaven. As the great prophet Khalil Gibran wrote On Marriage:</p>
<p><em>Fill each other's cup but drink not from one cup ...<br />
For the pillars of the temple stand apart,<br />
And the oak tree and the cypress grow not in each other's shadow</em></p>
<p>When one partner treats the other like a slave, a receptacle, like they need not be recognised and understood, divorce and domestic violence are only a short distance away. Refactoring is merely a set of steps on how to make the right choice for your <strong>next</strong> mail order bride, how to train them to do the chores. Fixes the symptom for this month, but it does not go anywhere near the causative problem.</p>
<ul>
<li><p>you can't "persist" object classes into a database. It is 2010, we have been writing ACID transactions for 30 years, not persistence objects. If you write persistence objects, you will have a single user app, with no concurrency, massively inefficient, full of broken transactions and data integrity problems.</p>
</li>
<li><p>you can't "design" databases like they are "object classes", because they aren't objects or classes. So stop wasting time, and learn how to design data in a multi-user location with some integrity. Or give the job to someone who knows how.</p>
</li>
<li><p>using OO notation or UML notation treats the database as a collection of objects, it only reinforces the Hammer, and makes sure it is the latest hardened steel with an imported Elm handle.</p>
</li>
<li><p>you can have a perfectly good marriage with a mail order bride. All it takes is a bit of recognition and respect.</p>
<ul>
<li><p>that means, learn the terminology and the notation. Even if you gave the job to someone skilled, when they give you the finished diagram, you need to understand it. that <strong>is</strong> the boundary. You can't go "EeeeK! I've never seen that before".</p>
</li>
<li><p>you can't have <em>some</em> of the features of the database, but <em>ignore</em> the other fundamental requirements. I am certainly not saying that it is all-or-nothing, that too is immature. But you have to have a basic understanding of the person you are marrying; the better the understanding, the better the marriage.</p>
</li>
<li><p>you cannot open the database box, without addressing multiple online users; concurrency (and thus data currency); transactions; data and referential integrity; etc. These idiots (Fowler and Ambler, not the readers) are re-inventing the wheel, and they have not reached the wooden spoke stage yet; they have not recognised that the fat round thing that is bolted together is the impedance itself. Their "persistence objects" suffer all the problems (such as Lost Updates, avoiding low concurrency) that we eliminated 30 years ago</p>
</li>
</ul>
</li>
<li><p>data that is modelled correctly does not change (it is easily extended, but that which exists, does not change). Apps come and go like ships. Object classes come and go with the developer. Therefore, if there were to be an order in the hierarchy (instead of an equal relationship), then the object should be modelled <strong>after</strong> the data.</p>
<ul>
<li><p>note also, that well written apps (to Standard) are impervious to such changes; apps which take the "database is a slave" approach are brittle, and break at the slightest change; these are grossly sub-standard apps. But the OO people do not see that, they see "Impedance Mismatch".</p>
</li>
<li><p>if (a) the app and the database have reasonable independence, and (b) the boundaries are clear, each side can be changed and extended without affecting the other side.</p>
</li>
<li><p>alternately, if the app is truly the one-and-only main event, then to make it successful (avoid "refactoring" every year or so; write it correctly, once, so that it lasts), forget about databases, keep your objects on the C:\ drive, and persist them.</p>
</li>
</ul>
</li>
</ul>
<p>That's why, twenty years ago, some of us were saying, publishing articles, that Ambler and Fowler have it backwards. It is no wonder they keep crashing into things and refactoring themselves.</p>
<p>It is noteworthy that the secret behind Agile, is that it is fully Normalised. That is a 180 degree change for Ambler, his published works, so it is no surprise that it is something he cannot herald and declare openly.</p>
<p>And just to make sure it doesn't get lost in the wash. The Notation is on the surface, but it is telling, of what is inside. IDEF1X tells you about the Relational mindset of the person who modelled the database. UML Notation for a "relational database" tells you the mindset of the person who factored the data heap, and who expects to refactor it many, many times. Choose carefully.</p>
<p>I have more than a Hammer in my toolbox.</p>
<ul>
<li>When I model data, I use IDEF1X</li>
<li>When I model functions, I use IDEF0 or SSADM (depending on the maturity of the users)</li>
<li>When I model objects, I use UML</li>
</ul>
<p>I ride horses, shoot deer, fight fires, and chase women. Each activity has a different set of principles and rules, which I must follow in order for me to succeed reasonably. Imagine what life would be like if I mixed them up. Or if I could only shoot.</p> |
4,576,271 | Monopoly game in OOD? | <p>I found this interesting blog post via CodingHorror: <a href="http://weblog.raganwald.com/2006/06/my-favourite-interview-question.html">My Favorite Interview Question</a>. In a nutshell, he talks about the object-oriented design challenges of designing the game of Monopoly, with an emphasis on how to model the rules of the game. For example, "If a player owns Baltic Avenue, can she add a house to it?"</p>
<p>Interestingly, near the bottom of the post, he then writes:</p>
<blockquote>
<p>You can probably save yourself a lot of interview time. Instead of all this hoopla, ask the candidate to describe when they have actually used the Strategy, Visitor, and Command patterns outside of a framework.)</p>
</blockquote>
<p>...which probably means that you can use design patterns to model the rules of the game (see above). Has anybody ever done this? Designed the game of Monopoly using design patterns? If so, how did it work out?</p> | 4,809,377 | 3 | 0 | null | 2011-01-01 23:19:31.93 UTC | 23 | 2011-01-28 23:35:12.283 UTC | 2011-01-26 21:47:54.227 UTC | null | 90,723 | null | 195,578 | null | 1 | 24 | oop|design-patterns|architecture | 10,634 | <p>Here's how I would design Monopoly. I've taken the liberty of assuming a dynamically-typed language since that makes everything easier. Ruby specifically.</p>
<p>You have a simple <code>Game</code> object that's mostly a wrapper around an <code>Array</code> of size 40, plus some convenience methods. The <code>Game</code> object also tracks the number of available <code>houses</code> and <code>hotels</code> and the two stacks of Chance and Community Chest cards. A few convenience methods like <code>current_turn</code> and <code>next_turn!</code> are provided — both return a <code>Player</code> object; <code>next_turn!</code> increments the turn index, wrapping to 0 if necessary.</p>
<p>All locations the player can land on must inherit from a superclass of <code>Property</code>. The <code>Property</code> class defines a few common things like <code>rent</code>, <code>owner</code>, <code>set</code>, <code>houses</code>, <code>purchasable?</code>, and <code>upgradeable?</code>. The <code>rent</code> and <code>owner</code> properties may be <code>nil</code>. The <code>set</code> property returns an <code>Array</code> containing all properties within the group. The <code>set</code> property may vary in size from 1 to 4. The <code>houses</code> property represents a hotel as 5 'houses'.</p>
<p>The <code>Game</code> object has an <code>Array</code> of <code>Player</code> objects, each with fields like <code>position</code> (an integer from 0 to 39), <code>money</code> (no upper bound — the bank technically never 'runs out of money'), <code>get_out_of_jail_frees</code>, and <code>in_jail?</code> (since position is insufficient for this). The <code>Game</code> object also has an index to track whose turn it is.</p>
<p>Property-specific rules are all encoded within their respective subclasses. So, for instance, the implementation of <code>rent</code> on a <code>Railroad</code> would be:</p>
<pre><code>def rent
owned_count = self.set.select { |rr| rr.owner == self.owner }.size
return 25 * 2 ** (owned_count - 1)
end
</code></pre>
<p>Chance and Community Chest cards can be simply implemented with a bunch of closures that takes a game and a player object as parameters. For instance:</p>
<pre><code># Second place in a beauty contest
COMMUNITY_CHEST_CARDS << lambda do |game, player|
player.money += 10
end
# Advance token to Boardwalk
CHANCE_CARDS << lambda do |game, player|
game.advance_token!(player, 39)
end
# Advance token to nearest railroad, pay double
CHANCE_CARDS << lambda do |game, player|
new_position = [5, 15, 25, 35].detect do |p|
p > player.position
end || 5
game.advance_token!(player, new_position)
# Pay rent again, no-op if unowned
game.properties[new_position].pay_rent!(player)
end
</code></pre>
<p>And so on. The <code>advance_token!</code> method obviously handles things like passing go.</p>
<p>Obviously, there are more details — it's a fairly complicated game, but hopefully this gives you the right idea. It'd certainly be more than sufficient for an interview.</p>
<h2>Update</h2>
<p>House rules could be switched on or off by adding a <code>house_rules</code> <code>Array</code> to the <code>Game</code> object. This would allow the <code>FreeParking</code> property to be implemented like this:</p>
<pre><code>class Game
def house_rules
@house_rules ||= []
end
def kitty
# Initialize the kitty to $500.
@kitty ||= 500
end
def kitty=(new_kitty)
@kitty = new_kitty
end
end
class FreeParking < Property
def rent
if self.game.house_rules.include?(:free_parking_kitty)
# Give the player the contents of the kitty, and then reset it to zero.
return -(_, self.game.kitty = self.game.kitty, 0)[0]
else
return 0
end
end
end
</code></pre> |
4,463,035 | How to force google closure compiler to keep "use strict"; in the compiled js code? | <p>If you're using the module pattern and have something like this:</p>
<pre><code>(function () {
"use strict";
// this function is strict...
}());
</code></pre>
<p>and compile the code using the Google Closure Compiler, the <code>"use strict";</code> directive will not make it into the compiled file.</p>
<p>So how do you prevent the Closure Compiler from removing the ES5/strict directive?</p>
<p>(Note that I don't want to use the other mode of enforcing ES5/strict mode, which is to simply add the "use strict"; to the first line of the compiled file. I want to use the module pattern as described <a href="http://www.yuiblog.com/blog/2010/12/14/strict-mode-is-coming-to-town/" rel="noreferrer">here</a>.)</p> | 4,582,220 | 5 | 0 | null | 2010-12-16 16:32:50.797 UTC | 9 | 2019-07-30 20:46:52.66 UTC | null | null | null | null | 86,302 | null | 1 | 32 | javascript|google-closure|google-closure-compiler|ecmascript-5 | 8,664 | <p>This isn't the greatest answer, but as far as I can tell this is a known issue or "feature" (depending on your perspective) of closure compiler. Here's a <a href="http://code.google.com/p/closure-compiler/issues/detail?id=69" rel="noreferrer">partial explanation</a> of some of the problems involved. A couple mentioned are that there's no way to preserve file-level strict mode declarations when multiple files are combined, and the compiler's function inlining feature would break the scope of function-level strict mode declarations. Since the behavior of "use strict" declarations would be unpredictable/wrong in compiled code (potentially breaking programs when strict mode is misapplied to non-strict code), the compiler strips them like any other dead code.</p>
<p>There seems to have been an idea to fully implement ECMAScript 5 strict mode checks in the compiler (in which case there would be no downside to removing it from compiled code), but it's not there yet.</p>
<p>Compiling in <code>SIMPLE_OPTIMIZATIONS</code> mode instead of <code>ADVANCED_OPTIMIZATIONS</code> will disable dead code removal, but I suspect you already know that.</p> |
4,454,444 | C++ libraries that implement Go goroutines or Go channels? | <p>I'm working with a medium-sized C++ code base which is currently entirely single-threaded. The time has come, however, to pursue concurrency and parallelism for performance gains. I'm very interested in the concurrency model of Google's Go programming language, with very lightweight goroutines and a system of communicating channels.</p>
<p>Sadly, for a variety of perfectly valid reasons, the project needs to stay in C++. So my question is: Is there a C++ library that approximates the Go paradigm for parallelism? Specifically, is there an approximation of goroutines or go channels available for C++? My fallback plan is just to use boost::thread.</p>
<p>The application in question is a long-running proprietary simulation for the financial forecasting domain. It's usually CPU bound, but also gets blocked on IO when new data become available. Many of the computations involved are not dependent on previous results and could be fairly easily made to run in parallel. Being able to run the application in a distributed context is a long-term goal, but not one that needs to be solved immediately.</p> | 4,455,814 | 6 | 4 | null | 2010-12-15 20:16:43.383 UTC | 13 | 2022-01-20 06:07:22.71 UTC | 2010-12-15 21:18:39 UTC | null | 298,036 | null | 298,036 | null | 1 | 29 | c++|concurrency|go | 13,150 | <p>If your aim is primarily speeding up compute things, Intel's <a href="https://www.threadingbuildingblocks.org/documentation/" rel="nofollow noreferrer">TBB</a> (Threading Building Blocks) is (IMHO) a better option than rolling your own inferior version from <code>boost::thread</code>.</p> |
4,560,288 | Python try/except: Showing the cause of the error after displaying my variables | <p>I'm not even sure what the right words are to search for. I want to display parts of the error object in an except block (similar to the err object in VBScript, which has Err.Number and Err.Description). For example, I want to show the values of my variables, then show the exact error. Clearly, I am causing a divided-by-zero error below, but how can I print that fact? </p>
<pre><code>try:
x = 0
y = 1
z = y / x
z = z + 1
print "z=%d" % (z)
except:
print "Values at Exception: x=%d y=%d " % (x,y)
print "The error was on line ..."
print "The reason for the error was ..."
</code></pre> | 4,560,341 | 7 | 0 | null | 2010-12-30 05:43:26.963 UTC | 15 | 2020-11-14 00:37:03.033 UTC | 2015-08-18 09:27:58.087 UTC | null | 3,001,761 | null | 160,245 | null | 1 | 44 | python|exception-handling | 85,799 | <pre><code>try:
1 / 0
except Exception as e:
print(e)
</code></pre> |
4,080,611 | #1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150) | <p>So I am trying to add a primary key to one of the tables in my database. Right now it has a primary key like this:</p>
<pre><code>PRIMARY KEY (user_id, round_number)
</code></pre>
<p>Where user_id is a foreign key.</p>
<p>I am trying to change it to this:</p>
<pre><code>PRIMARY KEY (user_id, round_number, created_at)
</code></pre>
<p>I am doing this in phpmyadmin by clicking on the primary key icon in the table structure view.</p>
<p>This is the error I get:</p>
<pre><code>#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)
</code></pre>
<p>It is a MySQL database with InnoDB table engine.</p> | 4,081,101 | 7 | 1 | null | 2010-11-02 17:55:17.963 UTC | 24 | 2018-07-01 19:28:34.863 UTC | 2011-04-30 17:29:46.803 UTC | null | 135,152 | null | 95,944 | null | 1 | 84 | mysql|sql|phpmyadmin|innodb|mysql-error-1025 | 106,589 | <p>There is probably another table with a foreign key referencing the primary key you are trying to change.</p>
<p>To find out which table caused the error you can run <code>SHOW ENGINE INNODB STATUS</code> and then look at the <code>LATEST FOREIGN KEY ERROR</code> section.</p> |
4,191,653 | I want to restore the database with a different schema | <p>I have taken a dump of a database named <code>temp1</code>, by using the follwing command </p>
<pre><code>$ pg_dump -i -h localhost -U postgres -F c -b -v -f pub.backup temp1
</code></pre>
<p>Now I want to restore the dump in a different database called "db_temp" , but in that I just want that all the tables should be created in a "temp_schema" ( not the default schema which is in the fms temp1 database ) which is in the "db_temp" database. </p>
<p>Is there any way to do this using <code>pg_restore</code> command?</p>
<p>Any other method also be appreciated!</p> | 4,194,781 | 8 | 9 | null | 2010-11-16 06:20:18.277 UTC | 22 | 2022-03-11 09:38:25.29 UTC | 2018-03-22 06:53:44.24 UTC | null | 263,268 | null | 283,501 | null | 1 | 83 | postgresql|pg-dump|pg-restore | 81,675 | <p>There's no way in pg_restore itself. What you can do is use pg_restore to generate SQL output, and then send this through for example a sed script to change it. You need to be careful about how you write that sed script though, so it doesn't match and change things inside your data.</p> |
4,224,476 | Float:right reverses order of spans | <p>I have the HTML:</p>
<pre><code><div>
<span class="label"><a href="/index/1">Bookmix Offline</a></span>
<span class="button"><a href="/settings/">Settings</a></span>
<span class="button"><a href="/export_all/">Export</a></span>
<span class="button"><a href="/import/">Import</a></span>
</div>
</code></pre>
<p>and CSS:</p>
<pre><code>span.button {
float:right;
}
span.label {
margin-left: 30px;
}
</code></pre>
<p>In the browser, spans display in the reverse order: Import Export Settings.
Can I change the order by changing only the CSS file and leave the HTML as is?</p> | 4,224,500 | 16 | 2 | null | 2010-11-19 11:22:50.547 UTC | 15 | 2019-09-21 13:41:08.003 UTC | 2016-07-29 18:31:29.473 UTC | null | 3,474,146 | null | 205,270 | null | 1 | 62 | css | 96,800 | <p>The general solution to this problem is either to reverse the order of the right floated elements in the HTML, or wrap them in a containing element and float that to the right instead.</p> |
14,819,994 | get basic SQL Server table structure information | <p>I can get the number of columns in an SQL Server database with this:</p>
<pre><code>SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'Address'
</code></pre>
<p>But is there any way (for an unknown number of columns) I can get the name and datatype and length of each column?</p> | 14,820,046 | 6 | 7 | null | 2013-02-11 20:10:06.167 UTC | 7 | 2018-07-06 11:51:51.237 UTC | 2013-02-11 20:22:44.217 UTC | null | 76,337 | null | 1,252,748 | null | 1 | 28 | sql|sql-server | 145,549 | <p>Instead of using <code>count(*)</code> you can <code>SELECT *</code> and you will return all of the details that you want including <code>data_type</code>:</p>
<pre><code>SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'Address'
</code></pre>
<p>MSDN Docs on <a href="http://msdn.microsoft.com/en-us/library/ms188348.aspx" rel="noreferrer"><code>INFORMATION_SCHEMA.COLUMNS</code></a></p> |
14,838,184 | Error: $digest already in progress | <p>I'm getting this error while trying to call </p>
<pre><code> function MyCtrl1($scope, $location, $rootScope) {
$scope.$on('$locationChangeStart', function (event, next, current) {
event.preventDefault();
var answer = confirm("Are you sure you want to leave this page?");
if (answer) {
$location.url($location.url(next).hash());
$rootScope.$apply();
}
});
}
MyCtrl1.$inject = ['$scope', '$location', '$rootScope'];
</code></pre>
<p>Error is</p>
<pre><code>Error: $digest already in progress
</code></pre> | 14,838,239 | 5 | 1 | null | 2013-02-12 17:23:57.477 UTC | 11 | 2016-11-18 20:35:44.77 UTC | 2013-02-12 17:29:42.113 UTC | null | 1,426,157 | null | 1,426,157 | null | 1 | 32 | javascript|angularjs|angularjs-directive | 71,348 | <p><strong>Duplicated: <a href="https://stackoverflow.com/questions/12729122/prevent-error-digest-already-in-progress-when-calling-scope-apply">Prevent error $digest already in progress when calling $scope.$apply()</a></strong></p>
<p>That error you are getting means Angular's dirty checking is already in progress.</p>
<p>Most recent best practices say that we should use <code>$timeout</code> if we want to execute any code in the next <em>digest</em> iteration:</p>
<pre><code>$timeout(function() {
// the code you want to run in the next digest
});
</code></pre>
<hr>
<p><strong>Previous response:</strong> (<a href="https://github.com/angular/angular.js/wiki/Anti-Patterns" rel="noreferrer">don't use this approach</a>)</p>
<p>Use a safe apply, like this:</p>
<pre><code>$rootScope.$$phase || $rootScope.$apply();
</code></pre>
<p>Why don't you invert the condition?</p>
<pre><code>$scope.$on('$locationChangeStart', function (event, next, current) {
if (confirm("Are you sure you want to leave this page?")) {
event.preventDefault();
}
});
</code></pre> |
14,663,397 | How to use labels inside loops with AngularJS | <p>So I'm inside an <code>ng-repeat</code> like this:</p>
<pre><code><li ng-repeat="x in xs">
<form>
<label for="UNIQUELABEL">name</label>
<input id="UNIQUELABEL">
<label for="ANOTHERUNIQUELABEL">name2</label>
<input id="ANOTHERUNIQUELABEL">
</form>
</li>
</code></pre>
<p>Which should produce something like</p>
<pre><code><li>
<form>
<label for="UNIQUELABEL1">name</label>
<input id="UNIQUELABEL1">
<label for="ANOTHERUNIQUELABEL1">name2</label>
<input id="ANOTHERUNIQUELABEL1">
</form>
</li>
<li>
<form>
<label for="UNIQUELABEL2">name</label>
<input id="UNIQUELABEL2">
<label for="ANOTHERUNIQUELABEL2">name2</label>
<input id="ANOTHERUNIQUELABEL2">
</form>
</li>
...
</code></pre>
<p>I'm new to AngularJS and not sure of the right way to approach this (none of the docs use <code>label</code> at all).</p> | 25,221,392 | 3 | 0 | null | 2013-02-02 15:29:22.08 UTC | 7 | 2017-11-13 10:03:38.227 UTC | null | null | null | null | 251,162 | null | 1 | 47 | html|angularjs | 23,712 | <p>Since <code>ng-repeat</code> provides a new scope object on each iteration, I prefer using something like</p>
<pre><code><li ng-repeat="x in xs">
<form>
<label for="UNIQUELABEL{{::$id}}_1">name</label>
<input id="UNIQUELABEL{{::$id}}_1">
<label for="UNIQUELABEL{{::$id}}_2">name2</label>
<input id="UNIQUELABEL{{::$id}}_2">
</form>
</li>
</code></pre>
<p>The advantage of this method is that you are guranteed not to have a duplicate selector with same id on the document. Duplicates could otherwise easily arise when routing or animating.</p> |
58,579,426 | In useEffect, what's the difference between providing no dependency array and an empty one? | <p>I gather that the <code>useEffect</code> Hook is run after every render, if provided with an empty dependency array:</p>
<pre class="lang-js prettyprint-override"><code>useEffect(() => {
performSideEffect();
}, []);
</code></pre>
<p>But what's the difference between that, and the following?</p>
<pre class="lang-js prettyprint-override"><code>useEffect(() => {
performSideEffect();
});
</code></pre>
<p>Notice the lack of <code>[]</code> at the end. The linter plugin doesn't throw a warning.</p> | 58,579,462 | 3 | 0 | null | 2019-10-27 12:28:09.057 UTC | 46 | 2022-06-16 22:32:27.007 UTC | 2020-02-13 15:40:19.12 UTC | null | 3,873,510 | null | 3,873,510 | null | 1 | 129 | reactjs|react-hooks|use-effect | 52,564 | <p>It's not quite the same. </p>
<ul>
<li><p>Giving it an empty array acts like <code>componentDidMount</code> as in, it only runs once.</p></li>
<li><p>Giving it no second argument acts as both <code>componentDidMount</code> and <code>componentDidUpdate</code>, as in it runs first on mount and then on every re-render.</p></li>
<li><p>Giving it an array as second argument with any value inside, eg <code>, [variable1]</code> will only execute the code inside your <code>useEffect</code> hook ONCE on mount, as well as whenever that particular variable (variable1) changes.</p></li>
</ul>
<p>You can read more about the second argument as well as more on how hooks actually work on the official docs at <a href="https://reactjs.org/docs/hooks-effect.html" rel="noreferrer">https://reactjs.org/docs/hooks-effect.html</a></p> |
38,844,103 | cannot use ^xxx outside of match clauses | <p>This function:</p>
<pre><code>defp entries(query, page_number, page_size) do
offset = page_size * (page_number - 1)
query
|> limit([_], ^page_size) # error
|> offset([_], ^offset)
|> Repo.all
end
</code></pre>
<p>gives an exception:</p>
<pre><code>cannot use ^pg_size outside of match clauses
</code></pre>
<p>Why is that and how to fix it?</p> | 38,844,355 | 4 | 0 | null | 2016-08-09 06:58:08.733 UTC | 1 | 2019-09-27 11:45:21.393 UTC | 2017-03-23 20:44:32.813 UTC | null | 4,376 | null | 6,644,400 | null | 1 | 39 | elixir|phoenix-framework|ecto | 9,087 | <p>This is most usually a sign that you haven't imported appropriate macros from <code>Ecto.Query</code>.</p> |
40,391,566 | Render Jinja after jQuery AJAX request to Flask | <p>I have a web application that gets dynamic data from <strong>Flask</strong> when a <strong>select</strong> element from HTML is changed. of course that is done via <strong>jquery ajax</strong>. No probs here I got that.</p>
<p>The problem is, the dynamic data <strong>- that is sent by Flask -</strong>, is a list of objects from the database <strong>Flask-sqlalchemy</strong>.</p>
<p>Of course the data is sent as <strong>JSON</strong> from <strong>Flask</strong>.</p>
<p>I'd like to iterate through those objects to display their info using <strong>Jinja</strong>.</p>
<h2>HTML</h2>
<pre><code><select id="#mySelect">
<option value="option1" id="1">Option 1 </option>
<option value="option2" id="1">Option 2 </option>
<option value="option3" id="3">Option 3 </option>
</select>
</code></pre>
<h2>jQuery</h2>
<pre><code>$('body').on('change','#mySelect',function(){
var option_id = $('#mySelect').find(':selected').attr('id');
$.ajax({
url: "{{ url_for('_get_content') }}",
type: "POST",
dataType: "json",
data: {'option_id':option_id},
success: function(data){
data = data.data;
/* HERE I WANT TO ITERATE THROUGH THE data LIST OF OBJECTS */
}
});
});
</code></pre>
<h2>Flask</h2>
<pre><code>@app.route('/_get_content/')
def _get_content():
option_id = request.form['option_id']
all_options = models.Content.query.filter_by(id=option_id)
return jsonify({'data': all_options})
</code></pre>
<h3>PS : I know that jinja gets rendered first so there is no way to assign jQuery variables to Jinja. So how exactly am I going to iterate through the data list if I can't use it in Jinja ?</h3> | 40,392,035 | 2 | 0 | null | 2016-11-02 23:37:01.657 UTC | 9 | 2016-11-03 12:30:08.153 UTC | null | null | null | null | 7,091,942 | null | 1 | 7 | jquery|python|ajax|flask|flask-sqlalchemy | 10,025 | <p>Okay, I got it.</p>
<p>Simply, I made an external <strong>html</strong> file and added the required <strong>jinja</strong> template to it.</p>
<pre><code>{% for object in object_list %}
{{object.name}}
{% endfor %}
</code></pre>
<p>then in my <strong>Flask</strong> file I literally returned the <strong>render_template</strong> response to the <strong>jquery</strong> ( which contained the <strong>HTML</strong> I wanted to append )</p>
<pre><code>objects_from_db = getAllObjects()
return jsonify({'data': render_template('the_temp.html', object_list=objects_from_db)}
</code></pre>
<p>And then simply append the HTML from the response to the required div to be updated.</p> |
40,760,274 | Add row to class diagram | <p>I am making a class diagram in draw.io, but I am completly new at it.</p>
<p>I am using the UML>Class2 figure.</p>
<p>The first three properties are part of the figure, but how do you get row number 4? </p>
<p>I assume there must be something so the text gets attached to the current figures.</p> | 40,815,539 | 4 | 0 | null | 2016-11-23 09:17:24.457 UTC | 4 | 2021-11-10 07:02:12.28 UTC | null | null | null | null | 2,854,001 | null | 1 | 72 | draw.io | 28,139 | <p>Select one of the existing rows and duplicate (ctrl/cmd-d or right click, select duplicate).</p> |
65,918,835 | When should I use Android Jetpack Compose Surface composable? | <p>There's <a href="https://developer.android.com/reference/kotlin/androidx/compose/material/package-summary#surface" rel="noreferrer">Surface</a> composable in Jetpack Compose which represents a <a href="https://material.io/design/environment/surfaces.html" rel="noreferrer">material surface</a>. A surface allows you to setup things like background color or border but it seems that the same might be done using <a href="https://developer.android.com/jetpack/compose/layout#modifiers" rel="noreferrer">modifiers</a>. When should I use the Surface composable and what the benefits it gives me?</p> | 65,918,836 | 3 | 0 | null | 2021-01-27 12:07:37.623 UTC | 6 | 2022-07-19 03:50:42.69 UTC | null | null | null | null | 4,858,777 | null | 1 | 41 | android|android-jetpack|android-jetpack-compose | 17,226 | <p><a href="https://developer.android.com/reference/kotlin/androidx/compose/material/package-summary#surface" rel="noreferrer">Surface</a> composable makes the code easier as well as explicitly indicates that the code uses a <a href="https://material.io/design/environment/surfaces.html" rel="noreferrer">material surface</a>. Let's see an example:</p>
<pre class="lang-kotlin prettyprint-override"><code>Surface(
color = MaterialTheme.colors.primarySurface,
border = BorderStroke(1.dp, MaterialTheme.colors.secondary),
shape = RoundedCornerShape(8.dp),
elevation = 8.dp
) {
Text(
text = "example",
modifier = Modifier.padding(8.dp)
)
}
</code></pre>
<p>and the result:</p>
<p><a href="https://i.stack.imgur.com/sTVIJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sTVIJ.png" alt="enter image description here" /></a></p>
<p>The same result can be achieved without Surface:</p>
<pre class="lang-kotlin prettyprint-override"><code>val shape = RoundedCornerShape(8.dp)
val shadowElevationPx = with(LocalDensity.current) { 2.dp.toPx() }
val backgroundColor = MaterialTheme.colors.primarySurface
Text(
text = "example",
color = contentColorFor(backgroundColor),
modifier = Modifier
.graphicsLayer(shape = shape, shadowElevation = shadowElevationPx)
.background(backgroundColor, shape)
.border(1.dp, MaterialTheme.colors.secondary, shape)
.padding(8.dp)
)
</code></pre>
<p>but it has a few drawbacks:</p>
<ul>
<li>The modifiers chain is pretty big and it isn't obvious that it implements a material surface</li>
<li>I have to declare a variable for the shape and pass it into three different modifiers</li>
<li>It uses <a href="https://developer.android.com/reference/kotlin/androidx/compose/material/package-summary#contentcolorfor" rel="noreferrer">contentColorFor</a> to figure out the content color while Surface does it under the hood. As a result the <code>backgroundColor</code> is used in two places as well.</li>
<li>I have to calculate the elevation in pixels</li>
<li><code>Surface</code> adjusts colors for elevation (in case of dark theme) <a href="https://material.io/design/color/dark-theme.html#properties" rel="noreferrer">according to the material design</a>. If you want the same behavior, it should be handled manually.</li>
</ul>
<p>For the full list of Surface features it's better to take a look at the <a href="https://developer.android.com/reference/kotlin/androidx/compose/material/package-summary#surface" rel="noreferrer">documentation</a>.</p> |
36,161,040 | Xcode 7.3 crashing when debugging with breakpoints | <p>I just install the Xcode 7.3 version. I can't debug at all because it's crashing when I try to use a breakpoint while I'm debugging. I tried removing Derive Data, Reboot my macbook, reinstall pods... but unfortunately nothing is working. Is someone having the same issue?</p>
<blockquote>
<p>Process: Xcode [2631]
Path: /Applications/Xcode.app/Contents/MacOS/Xcode
Identifier: com.apple.dt.Xcode
Version: 7.3 (10183.3)
Build Info: IDEFrameworks-10183003000000000~2
App Item ID: 497799835
App External ID: 816750016
Code Type: X86-64 (Native)
Parent Process: ??? [1]
Responsible: Xcode [2631]
User ID: 502</p>
<p>Date/Time: 2016-03-22 17:35:16.678 +0000
OS Version: Mac OS X 10.11.4 (15E65)
Report Version: 11
Anonymous UUID: 352BCE12-8AEF-A28A-B5F1-214B55269668</p>
<p>Time Awake Since Boot: 2500 seconds</p>
<p>System Integrity Protection: enabled</p>
<p>Crashed Thread: 30 Dispatch queue: DVTInvalidationPreventionQueue</p>
<p>Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000000
Exception Note: EXC_CORPSE_NOTIFY</p>
<p>VM Regions Near 0:
-->
__TEXT 00000001021a4000-00000001021a8000 [ 16K] r-x/rwx SM=COW /Applications/Xcode.app/Contents/MacOS/Xcode</p>
<p>Application Specific Information:
ProductBuildVersion: 7D175</p>
<p>Global Trace Buffer (reverse chronological seconds):
14.418349 DTXConnectionServices 0x000000010454fc3a initiating channel x1.c2 capability 642d65677561672d 766f72702d617461 654e2e7372656469 6174536b726f7774 0073636974736974
14.419261 DTXConnectionServices 0x000000010454fc3a initiating channel x1.c1 capability 756265642e65646f 2d65677561672d67 6f72702d61746164 702e737265646976 006f666e69636f72
71.740178 CFNetwork 0x00007fff8d398447 TCP Conn 0x7fe21e691b50 SSL Handshake DONE
72.390183 CFNetwork 0x00007fff8d398323 TCP Conn 0x7fe21e691b50 starting SSL negotiation
72.390333 CFNetwork 0x00007fff8d396ced TCP Conn 0x7fe21e691b50 complete. fd: 50, err: 0
72.390574 CFNetwork 0x00007fff8d4255c7 TCP Conn 0x7fe21e691b50 event 1. err: 0
72.582281 CFNetwork 0x00007fff8d395fbf TCP Conn 0x7fe21e691b50 started
72.628957 CFNetwork 0x00007fff8d359c42 Creating default cookie storage with process/bundle identifier
72.628957 CFNetwork 0x00007fff8d359bda Faulting in CFHTTPCookieStorage singleton
72.628976 CFNetwork 0x00007fff8d359a69 Faulting in NSHTTPCookieStorage singleton
72.650686 CFNetwork 0x00007fff8d457510 NSURLConnection finished with error - code -1100</p>
<p>Crashed Thread: 30 Dispatch queue: DVTInvalidationPreventionQueue</p>
<p>Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000000
Exception Note: EXC_CORPSE_NOTIFY</p>
<p>Thread 30 crashed with X86 Thread State (64-bit):
rax: 0x0000000000000000 rbx: 0x0000700003900628 rcx: 0x0000700003900338 rdx: 0x00007fe225f6d940
rdi: 0x0000700003900338 rsi: 0x000000000000003e rbp: 0x00007000039005f0 rsp: 0x00007000039003f0
r8: 0x0000000000000000 r9: 0x00007fe215375800 r10: 0xf6c0d10bcec3bd6e r11: 0x00007fe214fa1000
r12: 0x0000700003900628 r13: 0x0000000000000000 r14: 0x0000000000000001 r15: 0x00007fe215375800
rip: 0x000000010e3ae917 rfl: 0x0000000000000246 cr2: 0x0000000000000000</p>
</blockquote> | 36,172,742 | 3 | 0 | null | 2016-03-22 17:17:19.277 UTC | 7 | 2016-10-12 03:47:15.707 UTC | 2016-10-12 03:47:15.707 UTC | null | 1,373,798 | null | 921,789 | null | 1 | 42 | xcode|xcode7|xcode8 | 6,205 | <p>What solved it for me is setting the "Enable Clang Module Debugging" in Build Setting to NO.</p> |
35,971,589 | Angular 2 ngModelChange select option, grab a specific property | <p>I have a dropdown select form in angular 2. </p>
<p>Currently: When I select an option the <code>option name</code> gets passed into my <code>onChange</code> function as <code>$event</code> </p>
<p>Wanted: When I select an option I would like to pass <code>workout.id</code> into my <code>onChange</code> function. </p>
<p>How can I achieve that?</p>
<pre><code><select class="form-control" [ngModel]="selectedWorkout" (ngModelChange)="onChange($event)">
<option *ngFor="#workout of workouts">{{workout.name}}</option>
</select>
</code></pre>
<p><code>Controller</code></p>
<pre><code>onChange(value){
alert(JSON.stringify(value));
}
</code></pre> | 35,971,617 | 2 | 0 | null | 2016-03-13 14:41:02.903 UTC | 11 | 2017-08-25 05:47:46.3 UTC | null | null | null | null | 4,178,623 | null | 1 | 33 | angular | 79,721 | <pre><code><select class="form-control" [ngModel]="selectedWorkout" (ngModelChange)="onChange($event)">
<option *ngFor="#workout of workouts" [value]="workout.id">{{workout.name}}</option>
</select>
</code></pre>
<p>OR</p>
<pre><code><select class="form-control" [(ngModel)]="selectedWorkout" (change)="onChange($event.target.value)">
<option *ngFor="#workout of workouts" [value]="workout.id" >{{workout.name}}</option>
</select>
</code></pre>
<p><a href="http://plnkr.co/edit/kcgRsLgURAl4Lf8UzKvD?p=preview">check this</a></p> |
28,926,612 | PuTTY configuration equivalent to OpenSSH ProxyCommand | <p>I'm just trying to use PuTTY to get an SSH connection to my servers.
These servers allow incoming SSH connection only from another specific server ("MySshProxyingServer" in example below).</p>
<p>Using Linux this is no problem with the <code>ssh -W</code> command.</p>
<p>In PuTTY I can't find the options to create such a connection.</p>
<p>Example under Linux (<code>~/.ssh/config</code>):</p>
<pre><code>Host MyHostToConnectTo
Hostname xx.xx.xx.xx
User root
Identityfile ~/.ssh/id_rsa
ProxyCommand ssh MySshProxyServer -W %h:%p
</code></pre>
<p>Anyone knows how to use such a config in PuTTY?</p> | 28,937,185 | 2 | 0 | null | 2015-03-08 12:52:19.533 UTC | 10 | 2021-05-28 15:30:18.98 UTC | 2019-10-18 10:48:33.603 UTC | null | 850,848 | null | 4,646,609 | null | 1 | 37 | ssh|proxy|putty|portforwarding|openssh | 45,625 | <p>The equivalent in PuTTY is "local proxy command". You can use the <a href="https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter7.html" rel="noreferrer"><code>plink.exe</code></a> with the <a href="https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-ncmode" rel="noreferrer"><code>-nc</code> switch</a> instead of the <code>ssh</code> with the <code>-W</code> switch:</p>
<p><a href="https://i.stack.imgur.com/vCDtf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vCDtf.png" alt="PuTTY local proxy"></a></p>
<p>The <em>"local proxy command"</em> is:</p>
<pre><code>plink.exe %user@%proxyhost -P %proxyport -nc %host:%port
</code></pre>
<hr>
<p>An alternative is to open a tunnel via the "MySshProxyServer" first using another instance of PuTTY (or Plink).</p>
<p>See for example:</p>
<ul>
<li><a href="https://stackoverflow.com/q/4974131/850848">How to create SSH tunnel using PuTTY in Windows?</a></li>
<li><em>My</em> guide for <a href="https://winscp.net/eng/docs/guide_tunnel#tunnel_putty" rel="noreferrer">tunneling SFTP/SCP session</a>. It's for WinSCP, but just use PuTTY instead of WinSCP in section <a href="https://winscp.net/eng/docs/guide_tunnel#tunnel_putty_connecting" rel="noreferrer">Connecting through the tunnel</a>.</li>
</ul> |
44,482,788 | Using a Set data structure in React's state | <p>Is it possible to use ES6's <code>Set</code> data structure in React?</p>
<p>For example, if I have a checklist composed of distinct items, and I'd like to maintain each item's checked state. I'd like to write something like this:</p>
<pre><code>export default class Checklist extends React.Component {
constructor(props) {
super(props);
this.state = {
checkedItems: new Set()
}
}
addItem(item) {
//...?
}
removeItem(item) {
//...?
}
getItemCheckedStatus(item) {
return this.state.checkedItems.has(item);
}
// More code...
}
</code></pre>
<p>I understand there may be a problem with the fact that a Set is mutable by nature, and React performs a shallow comparison when updating the component, so it expects immutable objects to be passed and held in the state. However, is there a way to hold and maintain a Set object in the state?</p> | 44,482,908 | 2 | 0 | null | 2017-06-11 10:30:12.86 UTC | 10 | 2021-05-16 09:01:23.277 UTC | 2017-06-11 10:37:09.487 UTC | null | 1,989,647 | null | 1,989,647 | null | 1 | 63 | javascript|reactjs | 40,549 | <p>Since react will identify state changes only if the state property was replaced, and not mutated (shallow compare), you'll have to create a new Set from the old one, and apply the changes to it.</p>
<p>This is possible since <code>new Set(oldSet) !== oldSet</code>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const oldSet = new Set([1, 2]);
const newSet = new Set(oldSet);
console.log(oldSet === newSet);</code></pre>
</div>
</div>
</p>
<hr />
<p>How you use a Set in a class component:</p>
<pre><code>export default class Checklist extends React.Component {
constructor(props) {
super(props);
this.state = {
checkedItems: new Set()
}
this.addItem = this.addItem.bind(this);
this.removeItem = this.removeItem.bind(this);
}
addItem(item) {
this.setState(({ checkedItems }) => ({
checkedItems: new Set(checkedItems).add(item)
}));
}
removeItem(item) {
this.setState(({ checkedItems }) => {
const newChecked = new Set(checkedItems);
newChecked.delete(item);
return {
checkedItems: newChecked
};
});
}
getItemCheckedStatus(item) {
return this.state.checkedItems.has(item);
}
// More code...
}
</code></pre>
<hr />
<p>How to use a set with the <code>useState()</code> hook:</p>
<pre><code>const Comp = () => {
[state, setState] = useState(() => new Set());
const addItem = item => {
setState(prev => new Set(prev).add(item));
}
const removeItem = item => {
setState(prev => {
const next = new Set(prev);
next.delete(item);
return next;
});
}
return /* JSX */;
}
</code></pre> |
22,506,624 | How to make Octave use "gnuplot" instead of "fltk" by default? | <p>I'm using Octave 3.8 on Ubuntu 13.10 and "fltk" for graphics is not working well. So I always switch to "gnuplot" by commanding:</p>
<pre><code>graphics_toolkit("gnuplot")
</code></pre>
<p>How can I configure Octave to use "gnuplot" by default?</p> | 22,511,710 | 2 | 0 | null | 2014-03-19 12:58:54.317 UTC | 8 | 2016-05-25 14:20:22.37 UTC | null | null | null | null | 562,440 | null | 1 | 19 | octave | 33,344 | <p>You add the command to your <code>.octaverc</code> file.</p>
<p>For more info: <a href="http://www.gnu.org/software/octave/doc/interpreter/Startup-Files.html" rel="noreferrer">http://www.gnu.org/software/octave/doc/interpreter/Startup-Files.html</a></p> |
27,049,294 | Searchview doesn't work since app compat | <p>Since I implented app compat my searchview doesn't work anymore:</p>
<pre><code> Process: com.laurenswuyts.witpa, PID: 26666
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.SearchView.setSearchableInfo(android.app.SearchableInfo)' on a null object reference
at com.laurenswuyts.witpa.Activities.Events.EventActivity.onCreateOptionsMenu(EventActivity.java:75)
at android.app.Activity.onCreatePanelMenu(Activity.java:2820)
at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:275)
at android.support.v7.app.ActionBarActivity.superOnCreatePanelMenu(ActionBarActivity.java:276)
at android.support.v7.app.ActionBarActivityDelegate$1.onCreatePanelMenu(ActionBarActivityDelegate.java:79)
at android.support.v7.widget.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:49)
at android.support.v7.internal.app.ToolbarActionBar.populateOptionsMenu(ToolbarActionBar.java:459)
at android.support.v7.internal.app.ToolbarActionBar$1.run(ToolbarActionBar.java:69)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
</code></pre>
<p>So nullpointer for searchview while I have it:</p>
<pre><code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.event_main, menu);
// Get the SearchView and set the searchable configuration
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
return super.onCreateOptionsMenu(menu);
}
</code></pre>
<p>And in my menu I have this:</p>
<pre><code><!-- Search Widget -->
<item android:id="@+id/action_search"
android:title="@string/action_search"
android:icon="@drawable/ic_action_search"
app:showAsAction="always"
android:actionViewClass="android.support.v7.widget.SearchView"/>
</code></pre>
<p>I have no idea why it doesn't work anymore but it happened since I started using app compat 21.</p>
<p>Regards,</p> | 27,049,368 | 11 | 0 | null | 2014-11-20 20:49:46.247 UTC | 15 | 2022-05-09 19:11:59.56 UTC | null | null | null | null | 1,827,512 | null | 1 | 64 | java|android|search|menu|android-appcompat | 31,020 | <p>Try using the custom <code>app</code> namespace for your <code>actionViewClass</code> too:</p>
<pre><code>app:actionViewClass="android.support.v7.widget.SearchView"/>
</code></pre> |
34,357,617 | Append 2D array to 3D array, extending third dimension | <p>I have an array <code>A</code> that has shape <code>(480, 640, 3)</code>, and an array <code>B</code> with shape <code>(480, 640)</code>.</p>
<p>How can I append these two as one array with shape <code>(480, 640, 4)</code>? </p>
<p>I tried <code>np.append(A,B)</code> but it doesn't keep the dimension, while the <code>axis</code> option causes the <code>ValueError: all the input arrays must have same number of dimensions</code>.</p> | 34,357,652 | 2 | 0 | null | 2015-12-18 14:15:10.053 UTC | 6 | 2021-11-22 23:20:25.797 UTC | 2015-12-18 14:31:05.1 UTC | null | 3,923,281 | null | 5,600,651 | null | 1 | 38 | python|arrays|numpy|append | 69,198 | <p>Use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.dstack.html" rel="noreferrer"><code>dstack</code></a>:</p>
<pre><code>>>> np.dstack((A, B)).shape
(480, 640, 4)
</code></pre>
<p>This handles the cases where the arrays have different numbers of dimensions and stacks the arrays along the third axis.</p>
<p>Otherwise, to use <code>append</code> or <code>concatenate</code>, you'll have to make <code>B</code> three dimensional yourself and specify the axis you want to join them on:</p>
<pre><code>>>> np.append(A, np.atleast_3d(B), axis=2).shape
(480, 640, 4)
</code></pre> |
38,875,051 | Declare an array in TypeScript | <p>I'm having trouble either declaring or using a boolean array in Typescript, not sure which is wrong. I get an <code>undefined</code> error. Am I supposed to use JavaScript syntax or declare a new Array object? </p>
<p>Which one of these is the correct way to create the array?</p>
<pre><code>private columns = boolean[];
private columns = [];
private columns = new Array<boolean>();
</code></pre>
<p>How would I initialize all the values to be false?</p>
<p>How would I access the values, can I access them like, <code>columns[i] = true;</code>..?</p> | 38,875,301 | 5 | 1 | null | 2016-08-10 13:37:39.933 UTC | 33 | 2022-06-21 03:01:20.2 UTC | null | null | null | user3325783 | null | null | 1 | 162 | javascript|arrays|typescript | 257,134 | <p>Here are the different ways in which you can create an array of booleans in typescript:</p>
<pre><code>let arr1: boolean[] = [];
let arr2: boolean[] = new Array();
let arr3: boolean[] = Array();
let arr4: Array<boolean> = [];
let arr5: Array<boolean> = new Array();
let arr6: Array<boolean> = Array();
let arr7 = [] as boolean[];
let arr8 = new Array() as Array<boolean>;
let arr9 = Array() as boolean[];
let arr10 = <boolean[]>[];
let arr11 = <Array<boolean>> new Array();
let arr12 = <boolean[]> Array();
let arr13 = new Array<boolean>();
let arr14 = Array<boolean>();
</code></pre>
<p>You can access them using the index:</p>
<pre><code>console.log(arr[5]);
</code></pre>
<p>and you add elements using push:</p>
<pre><code>arr.push(true);
</code></pre>
<p>When creating the array you can supply the initial values:</p>
<pre><code>let arr1: boolean[] = [true, false];
let arr2: boolean[] = new Array(true, false);
</code></pre> |
53,253,350 | How to show roles of user discord.js / userinfo command | <p>I'm trying to make a <code>userinfo</code> command, and I'm currently stuck on showing roles of the user.</p>
<p>Here is my code:</p>
<pre><code>const Discord = module.require('discord.js');
const moment = require('moment');
module.exports.run = async (bot, message, args) => {
let user = message.mentions.users.first() || message.author;
const joinDiscord = moment(user.createdAt).format('llll');
const joinServer = moment(user.joinedAt).format('llll');
let embed = new Discord.RichEmbed()
.setAuthor(user.username + '#' + user.discriminator, user.displayAvatarURL)
.setDescription(`${user}`)
.setColor(`RANDOM`)
.setThumbnail(`${user.displayAvatarURL}`)
.addField('Joined at:', `${moment.utc(user.joinedAt).format('dddd, MMMM Do YYYY, HH:mm:ss')}`, true)
.addField('Status:', user.presence.status, true)
.addField('Roles:', user.roles.map(r => `${r}`).join(' | '), true)
.setFooter(`ID: ${user.id}`)
.setTimestamp();
message.channel.send({ embed: embed });
return;
}
module.exports.help = {
name: 'userinfo'
}
</code></pre>
<p>I'm getting this error <strong><code>TypeError: Cannot read property 'map' of undefined</code></strong> and I don't know how to fix it?</p> | 53,264,907 | 6 | 0 | null | 2018-11-11 21:21:29.43 UTC | 2 | 2021-01-02 03:09:55.62 UTC | 2020-05-26 11:37:56.203 UTC | null | 12,825,713 | null | 10,637,682 | null | 1 | 5 | javascript|bots|discord|discord.js | 42,831 | <p><a href="https://discord.js.org/#/docs/main/stable/class/User" rel="nofollow noreferrer"><code>User.roles</code></a> is <code>undefined</code> because that property doesn't exist: try using <a href="https://discord.js.org/#/docs/main/stable/class/GuildMember?scrollTo=roles" rel="nofollow noreferrer"><code>GuildMember.roles</code></a> instead:</p>
<pre><code>let member = message.mentions.members.first() || message.member,
user = member.user;
let embed = new Discord.RichEmbed()
// ... all the other stuff ...
.addField('Roles:', member.roles.map(r => `${r}`).join(' | '), true)
</code></pre>
<p>The other properties will still use <code>user</code>, but <code>.roles</code> will be related to the GuildMember.</p> |
38,040,327 | How to pass rustc flags to cargo? | <p>I am trying to disable dead code warnings. I tried the following</p>
<pre><code>cargo build -- -A dead_code
</code></pre>
<blockquote>
<p>➜ rla git:(master) ✗ cargo build -- -A dead_code
error: Invalid arguments.</p>
</blockquote>
<p>So I am wondering how would I pass rustc arguments to cargo?</p> | 38,040,431 | 2 | 0 | null | 2016-06-26 15:55:13.487 UTC | 10 | 2022-02-14 22:27:06.703 UTC | null | null | null | null | 944,430 | null | 1 | 32 | rust|rust-cargo | 27,412 | <p>You can pass flags through Cargo by several different means:</p>
<ul>
<li><code>cargo rustc</code>, which only affects your crate and not its dependencies.</li>
<li>The <a href="https://doc.rust-lang.org/cargo/reference/environment-variables.html" rel="noreferrer"><code>RUSTFLAGS</code></a> environment variable, which affects dependencies as well.</li>
<li>Some flags have a proper Cargo option, e.g., <code>-C lto</code> and <code>-C panic=abort</code> can be specified in the <code>Cargo.toml</code> file.</li>
<li>Add flags in <a href="https://doc.rust-lang.org/cargo/reference/config.html" rel="noreferrer"><code>.cargo/config</code></a> using one of the <code>rustflags=</code> keys.</li>
</ul>
<hr>
<p>However, in your specific case of configuring lints, you don't need to use compiler flags; you can also enable and disable lints directly in the source code using attributes. This may in fact be a better option as it's more robust, more targeted, and doesn't require you to alter your build system setup:</p>
<pre><code>#![deny(some_lint)] // deny lint in this module and its children
#[allow(another_lint)] // allow lint in this function
fn foo() {
...
}
</code></pre>
<p>See also:</p>
<ul>
<li><a href="https://stackoverflow.com/q/25877285/155423">How to disable unused code warnings in Rust?</a></li>
</ul> |
37,800,605 | Hadoop native libraries not found on OS/X | <p>I have downloaded <code>hadoop</code> source code from github and compiled with the <code>native</code> option:</p>
<pre><code>mvn package -Pdist,native -DskipTests -Dtar -Dmaven.javadoc.skip=true
</code></pre>
<p>I then copied the <code>.dylib</code> files to the $HADOOP_HOME/lib </p>
<pre><code>cp -p hadoop-common-project/hadoop-common/target/hadoop-common-2.7.1/lib/native/*.dylib /usr/local/Cellar/hadoop/2.7.2/libexec/share/hadoop/lib
</code></pre>
<p>The LD_LIBRARY_PATH was updated and hdfs restarted:</p>
<pre><code> echo $LD_LIBRARY_PATH
/usr/local/Cellar/hadoop/2.7.2/libexec/lib:
/usr/local/Cellar/hadoop/2.7.2/libexec/share/hadoop/common/lib:/Library/Java/JavaVirtualMachines/jdk1.8.0_92.jdk/Contents/Home//jre/lib
</code></pre>
<p>(Note: this also means that the answer to <a href="https://stackoverflow.com/questions/30369380/hadoop-unable-to-load-native-hadoop-library-for-your-platform-error-on-docker">Hadoop “Unable to load native-hadoop library for your platform” error on docker-spark?</a> does not work for me..)</p>
<p>But <code>checknative</code> still returns uniformly <code>false</code>:</p>
<pre><code>$stop-dfs.sh && start-dfs.sh && hadoop checknative
16/06/13 16:12:32 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Stopping namenodes on [sparkbook]
sparkbook: stopping namenode
localhost: stopping datanode
Stopping secondary namenodes [0.0.0.0]
0.0.0.0: stopping secondarynamenode
16/06/13 16:12:50 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
16/06/13 16:12:50 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Starting namenodes on [sparkbook]
sparkbook: starting namenode, logging to /usr/local/Cellar/hadoop/2.7.2/libexec/logs/hadoop-macuser-namenode-sparkbook.out
localhost: starting datanode, logging to /usr/local/Cellar/hadoop/2.7.2/libexec/logs/hadoop-macuser-datanode-sparkbook.out
Starting secondary namenodes [0.0.0.0]
0.0.0.0: starting secondarynamenode, logging to /usr/local/Cellar/hadoop/2.7.2/libexec/logs/hadoop-macuser-secondarynamenode-sparkbook.out
16/06/13 16:13:05 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
16/06/13 16:13:05 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Native library checking:
hadoop: false
zlib: false
snappy: false
lz4: false
bzip2: false
openssl: false
</code></pre> | 40,051,353 | 4 | 0 | null | 2016-06-13 23:16:10.067 UTC | 11 | 2019-08-22 19:25:41.387 UTC | 2019-08-22 19:25:41.387 UTC | null | 985,906 | null | 1,056,563 | null | 1 | 17 | macos|hadoop|hadoop-native-library | 14,697 | <p>To get this working on a fresh install of macOS 10.12, I had to do the following:</p>
<ol>
<li><p>Install build dependencies using <a href="http://brew.sh" rel="noreferrer">homebrew</a>:</p>
<pre><code>brew install cmake maven openssl [email protected] snappy
</code></pre></li>
<li><p>Check out hadoop source code</p>
<pre><code>git clone https://github.com/apache/hadoop.git
cd hadoop
git checkout rel/release-2.7.3
</code></pre></li>
<li><p>Apply the below patch to the build:</p>
<pre><code>diff --git a/hadoop-common-project/hadoop-common/src/CMakeLists.txt b/hadoop-common-project/hadoop-common/src/CMakeLists.txt
index 942b19c..8b34881 100644
--- a/hadoop-common-project/hadoop-common/src/CMakeLists.txt
+++ b/hadoop-common-project/hadoop-common/src/CMakeLists.txt
@@ -16,6 +16,8 @@
# limitations under the License.
#
+SET(CUSTOM_OPENSSL_PREFIX /usr/local/opt/openssl)
+
cmake_minimum_required(VERSION 2.6 FATAL_ERROR)
# Default to release builds
@@ -116,8 +118,8 @@ set(T main/native/src/test/org/apache/hadoop)
GET_FILENAME_COMPONENT(HADOOP_ZLIB_LIBRARY ${ZLIB_LIBRARIES} NAME)
SET(STORED_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES})
-set_find_shared_library_version("1")
-find_package(BZip2 QUIET)
+set_find_shared_library_version("1.0")
+find_package(BZip2 REQUIRED)
if (BZIP2_INCLUDE_DIR AND BZIP2_LIBRARIES)
GET_FILENAME_COMPONENT(HADOOP_BZIP2_LIBRARY ${BZIP2_LIBRARIES} NAME)
set(BZIP2_SOURCE_FILES
diff --git a/hadoop-common-project/hadoop-common/src/main/conf/core-site.xml b/hadoop-common-project/hadoop-common/src/main/conf/core-site.xml
index d2ddf89..ac8e351 100644
--- a/hadoop-common-project/hadoop-common/src/main/conf/core-site.xml
+++ b/hadoop-common-project/hadoop-common/src/main/conf/core-site.xml
@@ -17,4 +17,8 @@
<!-- Put site-specific property overrides in this file. -->
<configuration>
+<property>
+<name>io.compression.codec.bzip2.library</name>
+<value>libbz2.dylib</value>
+</property>
</configuration>
diff --git a/hadoop-tools/hadoop-pipes/pom.xml b/hadoop-tools/hadoop-pipes/pom.xml
index 34c0110..70f23a4 100644
--- a/hadoop-tools/hadoop-pipes/pom.xml
+++ b/hadoop-tools/hadoop-pipes/pom.xml
@@ -52,7 +52,7 @@
<mkdir dir="${project.build.directory}/native"/>
<exec executable="cmake" dir="${project.build.directory}/native"
failonerror="true">
- <arg line="${basedir}/src/ -DJVM_ARCH_DATA_MODEL=${sun.arch.data.model}"/>
+ <arg line="${basedir}/src/ -DJVM_ARCH_DATA_MODEL=${sun.arch.data.model} -DOPENSSL_ROOT_DIR=/usr/local/opt/openssl"/>
</exec>
<exec executable="make" dir="${project.build.directory}/native" failonerror="true">
<arg line="VERBOSE=1"/>
</code></pre></li>
<li><p>Build hadoop from source:</p>
<pre><code>mvn package -Pdist,native -DskipTests -Dtar -Dmaven.javadoc.skip=true
</code></pre></li>
<li><p>Specify <code>JAVA_LIBRARY_PATH</code> when running hadoop:</p>
<pre><code>$ JAVA_LIBRARY_PATH=/usr/local/opt/openssl/lib:/opt/local/lib:/usr/lib hadoop-dist/target/hadoop-2.7.3/bin/hadoop checknative -a
16/10/14 20:16:32 INFO bzip2.Bzip2Factory: Successfully loaded & initialized native-bzip2 library libbz2.dylib
16/10/14 20:16:32 INFO zlib.ZlibFactory: Successfully loaded & initialized native-zlib library
Native library checking:
hadoop: true /Users/admin/Desktop/hadoop/hadoop-dist/target/hadoop-2.7.3/lib/native/libhadoop.dylib
zlib: true /usr/lib/libz.1.dylib
snappy: true /usr/local/lib/libsnappy.1.dylib
lz4: true revision:99
bzip2: true /usr/lib/libbz2.1.0.dylib
openssl: true /usr/local/opt/openssl/lib/libcrypto.dylib
</code></pre></li>
</ol> |
23,578,427 | Changing primary key int type to serial | <p>Is there a way to change existing primary key type from int to serial without dropping the table? I already have a lot of data in the table and I don't want to delete it. </p> | 23,578,612 | 2 | 0 | null | 2014-05-10 07:39:06.143 UTC | 14 | 2017-02-15 09:55:34.423 UTC | 2017-02-15 09:55:34.423 UTC | null | 4,370,109 | null | 3,137,498 | null | 1 | 39 | postgresql|primary-key|auto-increment | 41,054 | <p>Converting an int to a serial <a href="http://www.postgresql.org/docs/9.3/static/datatype-numeric.html#DATATYPE-SERIAL" rel="noreferrer">more or less only means adding a sequence default to the value</a>, so to make it a serial;</p>
<ul>
<li><p>Pick a starting value for the serial, greater than any existing value in the table<br>
<code>SELECT MAX(id)+1 FROM mytable</code></p></li>
<li><p>Create a sequence for the serial (tablename_columnname_seq is a good name)<br>
<code>CREATE SEQUENCE test_id_seq MINVALUE 3</code> (assuming you want to start at 3)</p></li>
<li><p>Alter the default of the column to use the sequence<br>
<code>ALTER TABLE test ALTER id SET DEFAULT nextval('test_id_seq')</code></p></li>
<li><p>Alter the sequence to be owned by the table/column;<br>
<code>ALTER SEQUENCE test_id_seq OWNED BY test.id</code></p></li>
</ul>
<p><a href="http://sqlfiddle.com/#!15/7427c/1" rel="noreferrer">A very simple SQLfiddle demo</a>.</p>
<p>And as always, make a habit of running a full backup <em>before</em> running altering SQL queries from random people on the Internet ;-)</p> |
42,632,711 | How to call function on child component on parent events | <h2>Context</h2>
<p>In Vue 2.0 the documentation and <a href="http://taha-sh.com/blog/understanding-components-communication-in-vue-20" rel="noreferrer">others</a> clearly indicate that communication from parent to child happens via props.</p>
<h2>Question</h2>
<p>How does a parent tell its child an event has happened via props?</p>
<p>Should I just watch a prop called event? That doesn't feel right, nor do alternatives (<code>$emit</code>/<code>$on</code> is for child to parent, and a hub model is for distant elements).</p>
<h2>Example</h2>
<p>I have a parent container and it needs to tell its child container that it's okay to engage certain actions on an API. <strong>I need to be able to trigger functions.</strong> </p> | 45,463,576 | 11 | 1 | null | 2017-03-06 18:14:29.517 UTC | 74 | 2022-07-15 20:21:45.833 UTC | 2018-04-05 18:57:30.8 UTC | null | 1,218,980 | null | 1,399,513 | null | 1 | 279 | javascript|vue.js|event-handling|vuejs2 | 247,084 | <p>Give the child component a <code>ref</code> and use <code>$refs</code> to call a method on the child component directly.</p>
<p>html:</p>
<pre><code><div id="app">
<child-component ref="childComponent"></child-component>
<button @click="click">Click</button>
</div>
</code></pre>
<p>javascript:</p>
<pre><code>var ChildComponent = {
template: '<div>{{value}}</div>',
data: function () {
return {
value: 0
};
},
methods: {
setValue: function(value) {
this.value = value;
}
}
}
new Vue({
el: '#app',
components: {
'child-component': ChildComponent
},
methods: {
click: function() {
this.$refs.childComponent.setValue(2.0);
}
}
})
</code></pre>
<p>For more info, see <a href="https://v2.vuejs.org/v2/guide/components-edge-cases.html#Accessing-Child-Component-Instances-amp-Child-Elements" rel="nofollow noreferrer">Vue documentation on refs</a>.</p> |
7,681,821 | Passing objects to client in node + express + jade? | <p>I have a pretty heavyweight query on the server that results in a new page render, and I'd like to pass along some of the results of the query to the client (as a javascript array of objects). This is basically so I don't have to do a separate JSON query later to get the same content (which is mostly static). The data will be useful eventually, but not initially so I didn't put it directly into the document. </p>
<pre><code>app.get('/expensiveCall', function(req, res) {
// do expensive call
var data = veryExpensiveFunction();
res.render('expensiveCall.jade', {
locals: {
data: data,
}
});
});
});
</code></pre>
<p>data is a array of objects and only some are initially used. I'd like to pass either the entirety of data over or some subsets (depending on the situation). My jade looks like normal jade, but I would like to include something like</p>
<pre><code><script type="text/javascript">
var data = #{data};
</script>
</code></pre>
<p>but this doesn't work (it's an array of objects).</p> | 7,681,910 | 1 | 0 | null | 2011-10-07 00:00:27.447 UTC | 23 | 2011-10-07 11:49:11.443 UTC | null | null | null | null | 983,180 | null | 1 | 42 | json|node.js|express|pug | 27,549 | <p>You can't inline a JS object like that, but you can <code>JSON.stringify</code> it before:</p>
<pre><code><script type="text/javascript">
var data = !{JSON.stringify(data)};
</script>
</code></pre> |
22,568,354 | Jersey ClientBuilder.newClient(): source not found | <p>I have an Java 64-bit Eclipse application with Eclipse running on Windows 7 Pro x64.</p>
<p>I downloaded the <a href="https://jersey.java.net" rel="noreferrer">Jersey</a> bundle, jaxrs-ri-2.7.zip, for client RESTful API access.</p>
<p>I added these external jars (Project | Build Path | Configure Build Path... | Libraries):</p>
<pre><code>jaxrs-ri/api/javax.ws.rs-api-2.0.jar
jaxrs-ri/lib/jersey-client.jar
jaxrs-ri/lib/jersey-common.jar
</code></pre>
<p>Here is the source:</p>
<pre><code>package prjTestJersey;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
public static void main(String[] args)
{
try
{
Client oClient = ClientBuilder.newClient();
oClient.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
</code></pre>
<p>I receive the following error, when stepping over the first line, Clinet oClient...:</p>
<pre><code>Source not found.
</code></pre>
<p>Why the error and how do I fix it? Why "source not found" instead of a real error.</p>
<p>Note: I tried copying the 3 jar files to the project's lib folder, but that did not do any good. I am using the Eclipse debugger, so pressing F11 in debug view and then doing an F6 over the line.</p>
<p>UPDATE:</p>
<p>I tried creating a brand new 32-bit application (WindowBuilder SWT application window) and simply updated main(...), and same problem. That means the problem is platform independent.</p>
<p>UPDATE 2:</p>
<p>The posted answer to try running was not a bad idea. :-) That gave another clue, which I have to track down. Here is the dump.</p>
<pre><code>Exception in thread "main" java.lang.NoClassDefFoundError: org/glassfish/hk2/utilities/binding/AbstractBinder
at org.glassfish.jersey.client.ClientConfig.<init>(ClientConfig.java:452)
at org.glassfish.jersey.client.JerseyClientBuilder.<init>(JerseyClientBuilder.java:94)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at javax.ws.rs.client.FactoryFinder.newInstance(FactoryFinder.java:116)
at javax.ws.rs.client.FactoryFinder.find(FactoryFinder.java:206)
at javax.ws.rs.client.ClientBuilder.newBuilder(ClientBuilder.java:86)
at javax.ws.rs.client.ClientBuilder.newClient(ClientBuilder.java:114)
at AppMain.main(AppMain.java:20)
Caused by: java.lang.ClassNotFoundException: org.glassfish.hk2.utilities.binding.AbstractBinder
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 12 more
</code></pre>
<p>FINAL ANSWER:
(Thanks to both answers for the help.)</p>
<p>I was missing dependencies. The needed list is:</p>
<pre><code>swt_win32_x86.jar
api/javax.ws.rs-api-2.0.jar
ext/jersey-guava-2.7.jar
ext/hk2-api-2.2.0.jar
lib/jersey-common.jar
lib/jersey-client.jar
</code></pre> | 22,570,425 | 4 | 0 | null | 2014-03-21 19:56:13.437 UTC | 4 | 2019-11-12 12:48:54.327 UTC | 2014-03-21 23:08:01.093 UTC | null | 2,769,729 | null | 2,769,729 | null | 1 | 18 | java|eclipse|rest|jersey | 46,576 | <p>My guess is that "Source not found" simply is a message from Eclipse telling you it cannot debug into <code>Client oClient = ClientBuilder.newClient();</code> as you do not have the source code for the three jars attached in Eclipse. If you just run the program (without debugging) it might very well work. Read more here on how to add source code to jar files in Eclipse: <a href="https://stackoverflow.com/questions/122160/is-there-an-easy-way-to-attach-source-in-eclipse">Is there an easy way to attach source in Eclipse?</a>. </p>
<p>If it still doesn't work, I would suggest adding <strong>all</strong> the jars from the bundle you downloaded to make sure you aren't missing some dependency.</p> |
56,285,197 | What is the difference between enterAnim & popEnterAnim & exitAnim & popExitAnim? | <p>What is the difference between animation tags in latest Navigation Architecture Component? I got confused with <code>enterAnim</code> & <code>popEnterAnim</code>. Similarly, <code>exitAnim</code> & <code>popExitAnim</code>.</p>
<p>Any visual expansions is more than welcomed.</p> | 56,285,404 | 3 | 0 | null | 2019-05-24 02:44:13.253 UTC | 4 | 2022-01-11 08:22:45.353 UTC | null | null | null | null | 8,412,192 | null | 1 | 51 | android|android-animation|android-architecture-navigation | 6,898 | <p>The <a href="https://developer.android.com/guide/navigation/navigation-animate-transitions" rel="noreferrer">Animate transitions between destinations documentation</a> details the four types of animations:</p>
<blockquote>
<ul>
<li>Entering a destination</li>
<li>Exiting a destination</li>
<li>Entering a destination via a <a href="https://developer.android.com/guide/navigation/navigation-getting-started#pop" rel="noreferrer">pop action</a></li>
<li>Exiting a destination via a pop action</li>
</ul>
</blockquote>
<p>"Entering" refers to the destination that is coming onto the screen, while "exiting" refers to the destination leaving the screen.</p>
<p>Therefore when you navigate from destination <code>A</code> to destination <code>B</code>, the entering destination <code>B</code> will have the <code>enterAnim</code> applied to it and the exiting destination <code>A</code> will have the <code>exitAnim</code> applied to it.</p>
<p>When the user hits the system Back button, going from <code>B</code> <strong>back</strong> to <code>A</code>, the reverse happens: the entering destination <code>A</code> will have the <code>popEnterAnim</code> applied to it and the exiting destination <code>B</code> will have the <code>popExitAnim</code> applied to it.</p> |
2,546,780 | Python - animation with matplotlib.pyplot | <p>How can one create animated diagrams using popular matplotlib library? I am particularly interested in animated gifs.</p> | 2,547,625 | 3 | 0 | null | 2010-03-30 16:16:12.61 UTC | 9 | 2018-07-30 08:56:10.227 UTC | null | null | null | null | 215,571 | null | 1 | 23 | python|matplotlib | 36,083 | <p>The matplotlib docs provide an entire section of examples on <a href="http://matplotlib.sourceforge.net/examples/animation/index.html" rel="nofollow noreferrer">animation</a> (see this <a href="http://scipy-cookbook.readthedocs.io/items/Matplotlib_Animations.html" rel="nofollow noreferrer">scipy</a> tutorial also). Most, however, involve using the various GUI widget backends. There is one in there, "movie demo", that shows how to produce an avi of a series of PNGS. </p>
<p>To produce animated GIFs, I think your options are <a href="https://stackoverflow.com/questions/753190/programmatically-generate-video-or-animated-gif-in-python">pretty limited</a>. Last I checked, <a href="http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/" rel="nofollow noreferrer">PIL didn't support them</a>. You could however generate a series of PNGs using pyplot's savefig and then stitch them together using a call to ImageMagick or mencoder.</p> |
3,065,606 | When did the idea of macros (user-defined code transformation) appear? | <p>I have read McCarthy's 1960 paper on LISP and found no reference to anything that's similar to user-defined macros or normal order evaluation. I was wondering when macros first appeared in programming language history (and also in Lisp history):</p>
<ul>
<li>When was the idea of user-defined code transformation (before interpretation or compilation) first described (theoretically)?</li>
<li>What was the first programming language implementation to have Lisp-like macros (by "Lisp-like" I mean "using a readable Turing-complete language to do code-transformation")? (including non-Lisps -- Forth for example is quite old, but I'm not sure if the first Forth implementation already had "IMMEDIATE")</li>
<li>Also which of those was the first high-level programming language (exclude assembler languages...)</li>
<li>What was the first Lisp dialect to have macros?</li>
</ul>
<p>Thank you!</p> | 3,068,177 | 3 | 0 | null | 2010-06-17 20:59:49.637 UTC | 3 | 2019-05-15 05:13:20.913 UTC | 2016-02-11 17:04:50.613 UTC | null | 120,163 | null | 114,979 | null | 1 | 28 | macros|lisp|scheme|history|racket | 1,966 | <p>From <a href="http://www.dreamsongs.com/Files/HOPL2-Uncut.pdf" rel="noreferrer">The Evolution of Lisp</a> (Steele/Gabriel):</p>
<blockquote>
<p>3.3 Macros</p>
<p>Macros appear to have been introduced into Lisp by Timothy P. Hart in 1963 in a short MIT AI Memo [Hart, 1963],</p>
</blockquote>
<p>Timothy P. Hart, <a href="ftp://publications.ai.mit.edu/ai-publications/pdf/AIM-057.pdf" rel="noreferrer">MACRO Definitions for LISP</a>, October 1963</p> |
2,992,451 | How to subtract a year from the datetime? | <p>How to subtract a year from current datetime using c#?</p> | 2,992,457 | 3 | 0 | null | 2010-06-07 19:26:10.293 UTC | 4 | 2016-12-29 14:43:22.757 UTC | null | null | null | null | 144,842 | null | 1 | 97 | c# | 97,950 | <pre><code>var myDate = DateTime.Now;
var newDate = myDate.AddYears(-1);
</code></pre> |
2,513,415 | How to fix access to the requested resource which has been denied in Tomcat? | <p>I want to enable form based authentication by using database as realm but I'm always getting that message whenever I try to authenticate as Tomcat manager in Tomcat 6. I have already created a table user_name and user_roles and mapped the username(blue) to admin and manager as role in user_roles table in mysql, but I'm still unable to authenticate. I've already recreated realm tag in <code>server.xml</code> file:</p>
<pre><code> <Realm className = "org.apache.catalina.realm.JDBCRealm"
debug = "99"
driverName = "com.mysql.jdbc.Driver"
connectionURL = "jdbc:mysql://localhost:3306/mail"
connectionName = "root"
userTable = "users"
userNameCol = "user_name"
userCredCol = "user_pass"
userRoleTable = "user_roles"
roleNameCol = "role_name"
/>
</code></pre>
<p>Could anyone please tell me what's wrong I'm doing, and how I enable form based authentication by using database?</p>
<ol>
<li><p>I've declared the user "blue" as both admin and manager, and when I'm trying to login in tomcat manager page, it is giving me the message:</p>
<blockquote>
<p>HTTP Status 403 - Access to the requested resource has been denied</p>
</blockquote>
</li>
<li><p>When I enter wrong username or password, tomcat again asks for username and password instead of showing that message.</p>
</li>
</ol> | 2,514,501 | 4 | 2 | null | 2010-03-25 06:09:02.243 UTC | 2 | 2015-04-10 15:00:47.44 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 247,902 | null | 1 | 6 | tomcat|authentication|configuration|http-status-code-403|catalina | 45,732 | <p>I havent tried this myself. Can you try changing the auth-method in the <code>TOMCAT_HOME_DIR\webapps\manager\WEB-INF\web.xml</code> to point the auth-method set to FORM. The realm-name does not matter.</p>
<pre><code><login-config> <auth-method>FORM</auth-method> <realm-name>Tomcat Manager Application</realm-name> </login-config>
</code></pre>
<p>Also just confirm - you'll have to keep only one Realm in the server.xml, comment out the default one.</p> |
2,684,685 | Project structure in TFS 2010 | <p>We have just gotten TFS 2010 up and running. We will be migrating our source into TFS but I have a question on how to organize the code.</p>
<p>TFS 2010 has a new concept of project collections so I have decided that different groups within our organization will get their own group. My team develops many different web applications and we have several shared components. We also use a few third party components (such as telerik).</p>
<p>Clearly each web application is it's own project but where do I put the shared components? Should each component be in it's own project with separate builds and work items?</p>
<p>Is there a best practice or recommended way to do this specific to TFS 2010? </p> | 2,782,463 | 4 | 0 | null | 2010-04-21 16:20:04.413 UTC | 14 | 2020-07-09 10:33:08.233 UTC | 2020-07-09 10:33:08.233 UTC | null | 8,528,014 | null | 35,165 | null | 1 | 19 | tfs|tfs-2010 | 9,386 | <p>The best practice for this is to have everything that you need to build a solution under your Main/Trunk folder. We use the following format:</p>
<pre><code> "Project 1"
"DEV" (Folder)
"Feature 1" (Branch)
"Main" (Root branch)
"Release" (Folder)
"Release 1" (Branch)
"RTM" (Folder)
"Release 1.0" (Branch)
"Release 1.1" (Branch)
</code></pre>
<p>This keeps all of your branches at the same level so you do not have any doubt as to which is a branch and which is a folder.</p>
<p>That's your Team Project structure, but what about the actual folder structure under each of the branches:</p>
<pre><code>Main (Root branch)
"Builds" (Folder that contains all of the MSBuild and Workflows for building)
"Documents" (Folder that contains version specific documents)
"Deployment" (Folder that contains config required for deployment | We use TFS Deployer from Codeplex)
"Setup" (Folder contains all of the setup resources)
"[Company].[Namespace].*" (Folders that contains a project)
"Tools" ( Folder for all your nuts and bolts)
"Toolname" (Folder for a specific tool or reference library)
</code></pre>
<p>The idea is that it is the team's choice whether to use a new version of an external product or reference library. Just because one team can upgrade to a new version of NUnit does not mean that another team chooses not to as it is weeks of work.</p>
<p>By all means have a central "Tools" project that you always update with the latest and your team pulls from there, but do not have external dependencies. It makes it a nightmare to do automated builds and makes your developers upgrade even if it is not a good time. On top of that make sure you treat any external dependency as a Tool even if it is from another internal team. </p>
<p><strong>References:</strong> <a href="http://tfsdeployer.codeplex.com" rel="nofollow noreferrer">TFS Deployer</a></p> |
3,033,859 | Splitting every character of a string? | <p>I want to split a string into each single character. Eg:
Splitting : <code>"Geeta" to "G", "e", "e" , "t", "a"</code>
How can I do this? I want to split a string which don't have any separator
Please help.</p> | 3,033,867 | 4 | 0 | null | 2010-06-13 20:48:52.75 UTC | 2 | 2019-04-21 20:33:04.027 UTC | 2016-03-05 16:46:53.307 UTC | null | 3,313,438 | null | 365,870 | null | 1 | 29 | c#|string|split | 76,606 | <p><code>String.ToCharArray()</code></p>
<p>From <a href="https://msdn.microsoft.com/en-us/library/ezftk57x(v=vs.110).aspx" rel="noreferrer">MSDN</a>:</p>
<blockquote>
<p>This method copies each character (that is, each Char object) in a string to a character array. The first character copied is at index zero of the returned character array; the last character copied is at index Array.Length – 1.</p>
</blockquote> |
2,685,413 | What is the difference between a segmentation fault and a stack overflow? | <p>For example when we call say, a recursive function, the successive calls are stored in the stack. However, due to an error if it goes on infinitely the error is 'Segmentation fault' (as seen on GCC). </p>
<p>Shouldn't it have been 'stack-overflow'? What then is the basic difference between the two? </p>
<p>Btw, an explanation would be more helpful than wikipedia links (gone through that, but no answer to specific query).</p> | 2,685,434 | 4 | 4 | null | 2010-04-21 18:08:05.687 UTC | 28 | 2014-01-26 02:22:23.597 UTC | 2010-04-21 18:14:21.083 UTC | null | 40,468 | null | 297,353 | null | 1 | 36 | c|memory|stack|segmentation-fault|stack-overflow | 13,761 | <p>Stack overflow is [a] cause, segmentation fault is the result.</p>
<hr>
<p>At least on x86 and ARM, the "stack" is a piece of memory reserved for placing local variables and return addresses of function calls. When the stack is exhausted, the memory outside of the reserved area will be accessed. But the app did not ask the kernel for this memory, thus a SegFault will be generated for memory protection.</p> |
2,360,965 | What really is connection pooling? | <p>I have heard the term connection pooling and looked for some references by googling it... But can't get the idea when to use it....</p>
<ul>
<li><p>When should i consider using
connection pooling?</p></li>
<li><p>What are the advantages and
disadvantagesof connection pooling?</p></li>
</ul>
<p>Any suggestion....</p> | 2,360,981 | 6 | 8 | null | 2010-03-02 04:48:58.247 UTC | 10 | 2020-12-30 03:43:43.943 UTC | 2010-03-02 04:56:11.007 UTC | null | 207,556 | null | 207,556 | null | 1 | 24 | asp.net|connection-pooling | 6,664 | <p>The idea is that you do not open and close a single connection to your database, instead you create a "pool" of open connections and then reuse them. Once a single thread or procedure is done, it puts the connection back into the pool and, so that it is available to other threads. The idea behind it is that typically you don't have more than some 50 parallel connections and that opening a connection is time- and resource- consuming.</p> |
2,937,227 | What does (function($) {})(jQuery); mean? | <p>I am just starting out with writing jQuery plugins. I wrote three small plugins but I have been simply copying the line into all my plugins without actually knowing what it means. Can someone tell me a little more about these? Perhaps an explanation will come in handy someday when writing a framework :)</p>
<p>What does this do? (I know it extends jQuery somehow but is there anything else interesting to know about this)</p>
<pre><code>(function($) {
})(jQuery);
</code></pre>
<p>What is the difference between the following two ways of writing a plugin:</p>
<p><strong>Type 1:</strong></p>
<pre><code>(function($) {
$.fn.jPluginName = {
},
$.fn.jPluginName.defaults = {
}
})(jQuery);
</code></pre>
<p><strong>Type 2:</strong></p>
<pre><code>(function($) {
$.jPluginName = {
}
})(jQuery);
</code></pre>
<p><strong>Type 3:</strong></p>
<pre><code>(function($){
//Attach this new method to jQuery
$.fn.extend({
var defaults = {
}
var options = $.extend(defaults, options);
//This is where you write your plugin's name
pluginname: function() {
//Iterate over the current set of matched elements
return this.each(function() {
//code to be inserted here
});
}
});
})(jQuery);
</code></pre>
<p>I could be way off here and maybe all mean the same thing. I am confused. In some cases, <strong>this</strong> doesn't seem to be working in a plugin that I was writing using Type 1. So far, Type 3 seems the most elegant to me but I'd like to know about the others as well.</p> | 2,937,256 | 6 | 3 | null | 2010-05-30 01:36:57.727 UTC | 194 | 2020-06-17 13:08:58.253 UTC | 2011-08-08 15:30:22.59 UTC | null | 560,648 | null | 184,046 | null | 1 | 319 | javascript|jquery | 257,849 | <p>Firstly, a code block that looks like <code>(function(){})()</code> is merely a function that is executed in place. Let's break it down a little.</p>
<pre><code>1. (
2. function(){}
3. )
4. ()
</code></pre>
<p>Line 2 is a plain function, wrapped in parenthesis to tell the runtime to return the function to the parent scope, once it's returned the function is executed using line 4, maybe reading through these steps will help</p>
<pre><code>1. function(){ .. }
2. (1)
3. 2()
</code></pre>
<p>You can see that 1 is the declaration, 2 is returning the function and 3 is just executing the function.</p>
<p>An example of how it would be used.</p>
<pre><code>(function(doc){
doc.location = '/';
})(document);//This is passed into the function above
</code></pre>
<p>As for the other questions about the plugins:</p>
<p>Type 1: This is not a actually a plugin, it's an object passed as a function, as plugins tend to be functions.</p>
<p>Type 2: This is again not a plugin as it does not extend the <code>$.fn</code> object. It's just an extenstion of the jQuery core, although the outcome is the same. This is if you want to add traversing functions such as toArray and so on.</p>
<p>Type 3: This is the best method to add a plugin, the extended prototype of jQuery takes an object holding your plugin name and function and adds it to the plugin library for you.</p> |
2,487,844 | Simple way to show the 'Copy' popup on UITableViewCells like the address book App | <p>Is there a simple way for subclasses of UITableViewCell to show the 'Copy' UIMenuController popup like in the Address book app (see screenshot), after the selection is held for a while?</p>
<p><a href="https://i.stack.imgur.com/s1AAj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s1AAj.png" alt="address book" /></a><br />
<sub>(source: <a href="https://icog.net/files/IMG_0920.PNG" rel="nofollow noreferrer">icog.net</a>)</sub></p> | 2,488,237 | 7 | 0 | null | 2010-03-21 16:49:01.253 UTC | 26 | 2021-04-12 14:05:23.893 UTC | 2021-04-12 14:05:23.893 UTC | null | 4,751,173 | null | 72,176 | null | 1 | 42 | ios|objective-c|iphone|uitableview|pasteboard | 21,994 | <p>The method before iOS 5 is to get the UIMenuController's shared instance, set the target rect and view and call <code>-setMenuVisible:animated:</code>. Remeber to implement <code>-canPerformAction:withSender:</code> in your responder.</p>
<hr>
<p>The method after iOS 5 (previously available as undocumented feature) is to implement these 3 methods in your data source (see <a href="https://developer.apple.com/reference/uikit/uitableviewdelegate#1653389" rel="noreferrer">https://developer.apple.com/reference/uikit/uitableviewdelegate#1653389</a>).</p>
<pre><code>-(void)tableView:(UITableView*)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath*)indexPath withSender:(id)sender;
-(BOOL)tableView:(UITableView*)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath*)indexPath withSender:(id)sender;
-(BOOL)tableView:(UITableView*)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath*)indexPath;
</code></pre> |
2,724,864 | What is the difference between C# and .NET? | <p>May I know what is the difference between C# and .NET? When I think of C#, right away I would say it is a .NET language, but when I search for job posts, they require candidates to have C# and .NET experience. Can someone give me an explanation?</p> | 2,724,907 | 11 | 3 | null | 2010-04-27 20:31:22.273 UTC | 57 | 2022-08-09 20:11:07.41 UTC | 2013-07-17 17:08:09.697 UTC | null | 555,544 | null | 64,398 | null | 1 | 270 | c#|.net | 401,460 | <p>In addition to <a href="https://stackoverflow.com/a/2724872/10251345">Andrew's answer</a>, it is worth noting that:</p>
<ul>
<li>.NET isn't just a <strong>library</strong>, but also a <strong>runtime</strong> for executing applications.</li>
<li>The knowledge of C# implies some knowledge of .NET (because the C# object model corresponds to the .NET object model and you can do something interesting in C# just by using .NET libraries). The opposite isn't necessarily true as you can use other languages to write .NET applications.</li>
</ul>
<p>The distinction between a <em>language</em>, a <em>runtime</em>, and a <em>library</em> is more strict in .NET/C# than for example in C++, where the language specification also includes some basic library functions. The C# specification says only a very little about the environment (basically, that it should contain some types such as <code>int</code>, but that's more or less all).</p> |
2,658,772 | Vertical line using XML drawable | <p>I'm trying to figure out how to define a vertical line (1dp thick) to be used as a drawable.</p>
<p>To make a horizontal one, it's pretty straightforward:</p>
<pre><code><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="line">
<stroke android:width="1dp" android:color="#0000FF"/>
<size android:height="50dp" />
</shape>
</code></pre>
<p>The question is, how to make this line vertical?</p>
<p>Yes, there are workarounds, such as drawing a rectangle shape 1px thick, but that complicates the drawable XML, if it consists of multiple <code><item></code> elements.</p>
<p>Anyone had any chance with this?</p>
<p><strong>UPDATE</strong></p>
<p>Case is still unsolved. However,
For anyone on a Android documentation crusade - you might find this useful:
<strong><a href="http://idunnolol.com/android/drawables.html" rel="noreferrer">Missing Android XML Manual</a></strong> </p>
<p><strong>UPDATE</strong></p>
<p>I found no other way other than the one that I marked as correct. It does the trick though feels a bit "heavy", thus if you happen to know the answer don't forget to share ;)</p> | 2,659,038 | 18 | 0 | null | 2010-04-17 14:57:01.76 UTC | 59 | 2021-08-06 07:39:29.647 UTC | 2013-12-30 13:51:24.66 UTC | null | 56,285 | null | 55,583 | null | 1 | 183 | android|android-layout|line|android-xml|android-drawable | 269,115 | <p>Instead of a shape, you could try a <code>View</code>:</p>
<pre><code><View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#FF0000FF" />
</code></pre>
<p>I have only used this for horizontal lines, but I would think it would work for vertical lines as well.</p>
<p>Use:</p>
<pre><code><View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#FF0000FF" />
</code></pre>
<p>for a horizontal line.</p> |
45,401,734 | How to work with DTO in Spring Data REST projects? | <p>Spring Data REST automates exposing only domain object. But most often we have to deal with Data Transfer Objects. So how to do this in SDR way?</p> | 45,401,735 | 1 | 0 | null | 2017-07-30 15:51:58.61 UTC | 17 | 2017-07-30 15:51:58.61 UTC | null | null | null | null | 5,380,322 | null | 1 | 18 | spring|spring-data-rest|projection|dto | 17,819 | <p><strong>An approach of how to work with <a href="https://en.wikipedia.org/wiki/Data_transfer_object" rel="noreferrer">DTO</a> in <a href="https://projects.spring.io/spring-data-rest/" rel="noreferrer">Spring Data REST</a> projects</strong></p>
<p><em>The working example is <a href="https://github.com/Cepr0/spring-data-rest-dto" rel="noreferrer">here</a></em></p>
<p><strong>Entities</strong></p>
<p>Entities must implement the <a href="http://docs.spring.io/spring-hateoas/docs/current-SNAPSHOT/api/org/springframework/hateoas/Identifiable.html" rel="noreferrer">Identifiable</a> interface. For example:</p>
<pre class="lang-java prettyprint-override"><code>@Entity
public class Category implements Identifiable<Integer> {
@Id
@GeneratedValue
private final Integer id;
private final String name;
@OneToMany
private final Set<Product> products = new HashSet<>();
// skipped
}
@Entity
public class Product implements Identifiable<Integer> {
@Id
@GeneratedValue
private final Integer id;
private final String name;
// skipped
}
</code></pre>
<p><strong>Projections</strong></p>
<p>Make a <a href="https://spring.io/blog/2016/05/03/what-s-new-in-spring-data-hopper#projections-on-repository-query-methods" rel="noreferrer">projection</a> interface that repository query methods will return:</p>
<pre class="lang-java prettyprint-override"><code>public interface CategoryProjection {
Category getCategory();
Long getQuantity();
}
</code></pre>
<p>It will be a basement for DTO. In this example DTO will represent a <code>Category</code> and the number of <code>Product</code>s are belong to it.</p>
<p><strong>Repository methods</strong></p>
<p>Create methods return the projection: a single one, a list of DTO and a paged list of DTO.</p>
<pre class="lang-java prettyprint-override"><code>@RepositoryRestResource
public interface CategoryRepo extends JpaRepository<Category, Integer> {
@RestResource(exported = false)
@Query("select c as category, count(p) as quantity from Category c join c.products p where c.id = ?1 group by c")
CategoryProjection getDto(Integer categoryId);
@RestResource(exported = false)
@Query("select c as category, count(p) as quantity from Category c join c.products p group by c")
List<CategoryProjection> getDtos();
@RestResource(exported = false)
@Query("select c as category, count(p) as quantity from Category c join c.products p group by c")
Page<CategoryProjection> getDtos(Pageable pageable);
}
</code></pre>
<p><strong>DTO</strong> </p>
<p>Implement DTO from its interface:</p>
<pre class="lang-java prettyprint-override"><code>@Relation(value = "category", collectionRelation = "categories")
public class CategoryDto implements CategoryProjection {
private final Category category;
private final Long quantity;
// skipped
}
</code></pre>
<p>Annotation <code>Relation</code> is used when Spring Data REST is rendering the object.</p>
<p><strong>Controller</strong></p>
<p>Add custom methods to <code>RepositoryRestController</code> that will serve requests of DTO:</p>
<pre class="lang-java prettyprint-override"><code>@RepositoryRestController
@RequestMapping("/categories")
public class CategoryController {
@Autowired private CategoryRepo repo;
@Autowired private RepositoryEntityLinks links;
@Autowired private PagedResourcesAssembler<CategoryProjection> assembler;
/**
* Single DTO
*/
@GetMapping("/{id}/dto")
public ResponseEntity<?> getDto(@PathVariable("id") Integer categoryId) {
CategoryProjection dto = repo.getDto(categoryId);
return ResponseEntity.ok(toResource(dto));
}
/**
* List of DTO
*/
@GetMapping("/dto")
public ResponseEntity<?> getDtos() {
List<CategoryProjection> dtos = repo.getDtos();
Link listSelfLink = links.linkFor(Category.class).slash("/dto").withSelfRel();
List<?> resources = dtos.stream().map(this::toResource).collect(toList());
return ResponseEntity.ok(new Resources<>(resources, listSelfLink));
}
/**
* Paged list of DTO
*/
@GetMapping("/dtoPaged")
public ResponseEntity<?> getDtosPaged(Pageable pageable) {
Page<CategoryProjection> dtos = repo.getDtos(pageable);
Link pageSelfLink = links.linkFor(Category.class).slash("/dtoPaged").withSelfRel();
PagedResources<?> resources = assembler.toResource(dtos, this::toResource, pageSelfLink);
return ResponseEntity.ok(resources);
}
private ResourceSupport toResource(CategoryProjection projection) {
CategoryDto dto = new CategoryDto(projection.getCategory(), projection.getQuantity());
Link categoryLink = links.linkForSingleResource(projection.getCategory()).withRel("category");
Link selfLink = links.linkForSingleResource(projection.getCategory()).slash("/dto").withSelfRel();
return new Resource<>(dto, categoryLink, selfLink);
}
}
</code></pre>
<p>When Projections are received from repository we must make the final transformation from a Projection to DTO
and 'wrap' it to <a href="http://docs.spring.io/spring-hateoas/docs/current-SNAPSHOT/api/org/springframework/hateoas/ResourceSupport.html" rel="noreferrer">ResourceSupport</a> object before sending to the client.
To do this we use helper method <code>toResource</code>: we create a new DTO, create necessary links for this object,
and then create a new <code>Resource</code> with the object and its links. </p>
<p><strong>Result</strong></p>
<p><em>See the API docs on the <a href="https://documenter.getpostman.com/view/788154/spring-data-rest-dto/6mz3FWE" rel="noreferrer">Postman site</a></em> </p>
<p><strong>Singe DTO</strong></p>
<pre><code>GET http://localhost:8080/api/categories/6/dto
</code></pre>
<pre class="lang-json prettyprint-override"><code>{
"category": {
"name": "category1"
},
"quantity": 3,
"_links": {
"category": {
"href": "http://localhost:8080/api/categories/6"
},
"self": {
"href": "http://localhost:8080/api/categories/6/dto"
}
}
}
</code></pre>
<p><strong>List of DTO</strong></p>
<pre><code>GET http://localhost:8080/api/categories/dto
</code></pre>
<pre class="lang-json prettyprint-override"><code>{
"_embedded": {
"categories": [
{
"category": {
"name": "category1"
},
"quantity": 3,
"_links": {
"category": {
"href": "http://localhost:8080/api/categories/6"
},
"self": {
"href": "http://localhost:8080/api/categories/6/dto"
}
}
},
{
"category": {
"name": "category2"
},
"quantity": 2,
"_links": {
"category": {
"href": "http://localhost:8080/api/categories/7"
},
"self": {
"href": "http://localhost:8080/api/categories/7/dto"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/api/categories/dto"
}
}
}
</code></pre>
<p><strong>Paged list of DTO</strong></p>
<pre><code>GET http://localhost:8080/api/categories/dtoPaged
</code></pre>
<pre class="lang-json prettyprint-override"><code>{
"_embedded": {
"categories": [
{
"category": {
"name": "category1"
},
"quantity": 3,
"_links": {
"category": {
"href": "http://localhost:8080/api/categories/6"
},
"self": {
"href": "http://localhost:8080/api/categories/6/dto"
}
}
},
{
"category": {
"name": "category2"
},
"quantity": 2,
"_links": {
"category": {
"href": "http://localhost:8080/api/categories/7"
},
"self": {
"href": "http://localhost:8080/api/categories/7/dto"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/api/categories/dtoPaged"
}
},
"page": {
"size": 20,
"totalElements": 2,
"totalPages": 1,
"number": 0
}
}
</code></pre> |
Subsets and Splits