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
19,455,059
Allow user to resize an undecorated Stage
<p>I am working on making a screen recorder in JavaFX and one utility that is mandatory in the screen recorder is to let the user define how much area to record. </p> <p>I managed to make an undecorated , semi-transparent <code>Stage</code> that can be dragged around to define the area and added a <code>close</code> button to let the user confirm the area which is to be recorded. </p> <p><strong>Now, how do I let the user resize the stage by dragging it by its edges ?</strong> </p> <p>SSCCE: </p> <pre><code>package draggable; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.geometry.Rectangle2D; import javafx.scene.Scene; import javafx.scene.SceneBuilder; import javafx.scene.control.Button; import javafx.scene.control.ButtonBuilder; import javafx.scene.input.MouseEvent; import javafx.scene.layout.StackPane; import javafx.scene.layout.StackPaneBuilder; import javafx.scene.paint.Color; import javafx.stage.Screen; import javafx.stage.Stage; import javafx.stage.StageStyle; public class DraggableStage extends Application{ Button close; StackPane holder; Rectangle2D maxBounds; Scene theScene; double pressedX; double pressedY; double draggedX; double draggedY; @Override public void start(Stage stage) throws Exception { final Stage theStage = stage; // determine how big the screen is maxBounds = Screen.getPrimary().getVisualBounds(); //create the close button close = ButtonBuilder .create() .text("Close") .build(); //create the StackPane holder for the button holder = StackPaneBuilder .create() .alignment(Pos.CENTER) .children(close) .build(); // you cannot resize the screen beyond the max resolution of the screen holder.setMaxSize(maxBounds.getWidth(), maxBounds.getHeight()); //you cannot resize under half the width and height of the screen holder.setMinSize(maxBounds.getWidth() / 2,maxBounds.getHeight() / 2); //the scene where it all happens theScene = SceneBuilder .create() .root(holder) .width(maxBounds.getWidth() / 2) .height(maxBounds.getHeight() / 2) .build(); // add the button listeners close.setOnAction(new EventHandler&lt;ActionEvent&gt;(){ @Override public void handle(ActionEvent event) { theStage.close(); } }); // add the drag and press listener for the StackPane holder.setOnMousePressed(new EventHandler&lt;MouseEvent&gt;(){ @Override public void handle(MouseEvent e) { pressedX = e.getX(); pressedY = e.getY(); } }); holder.setOnMouseDragged(new EventHandler&lt;MouseEvent&gt;(){ @Override public void handle(MouseEvent e) { draggedX = e.getX(); draggedY = e.getY(); double differenceX = draggedX - pressedX; double differenceY = draggedY - pressedY; theStage.setX(theStage.getX() + differenceX); theStage.setY(theStage.getY() + differenceY); } }); //the mandatory mumbo jumbo theScene.setFill(Color.rgb(128, 128, 128, 0.5)); stage.initStyle(StageStyle.TRANSPARENT); stage.setScene(theScene); stage.sizeToScene(); stage.show(); } public static void main(String[] args) { Application.launch("draggable.DraggableStage"); } } </code></pre> <p>Image:<br> <img src="https://i.stack.imgur.com/UUDes.png" alt="enter image description here"></p>
24,017,605
13
5
null
2013-10-18 16:55:23.27 UTC
13
2021-03-05 02:03:31.093 UTC
null
null
null
null
1,894,684
null
1
25
java|javafx-2|stage|scene
13,595
<p>I created a ResizeHelper class which can help you in that case, usage: </p> <pre><code>ResizeHelper.addResizeListener(yourStage); </code></pre> <p>the helper class:</p> <pre><code>import javafx.collections.ObservableList; import javafx.event.EventHandler; import javafx.event.EventType; import javafx.scene.Cursor; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.input.MouseEvent; import javafx.stage.Stage; //created by Alexander Berg public class ResizeHelper { public static void addResizeListener(Stage stage) { ResizeListener resizeListener = new ResizeListener(stage); stage.getScene().addEventHandler(MouseEvent.MOUSE_MOVED, resizeListener); stage.getScene().addEventHandler(MouseEvent.MOUSE_PRESSED, resizeListener); stage.getScene().addEventHandler(MouseEvent.MOUSE_DRAGGED, resizeListener); stage.getScene().addEventHandler(MouseEvent.MOUSE_EXITED, resizeListener); stage.getScene().addEventHandler(MouseEvent.MOUSE_EXITED_TARGET, resizeListener); ObservableList&lt;Node&gt; children = stage.getScene().getRoot().getChildrenUnmodifiable(); for (Node child : children) { addListenerDeeply(child, resizeListener); } } public static void addListenerDeeply(Node node, EventHandler&lt;MouseEvent&gt; listener) { node.addEventHandler(MouseEvent.MOUSE_MOVED, listener); node.addEventHandler(MouseEvent.MOUSE_PRESSED, listener); node.addEventHandler(MouseEvent.MOUSE_DRAGGED, listener); node.addEventHandler(MouseEvent.MOUSE_EXITED, listener); node.addEventHandler(MouseEvent.MOUSE_EXITED_TARGET, listener); if (node instanceof Parent) { Parent parent = (Parent) node; ObservableList&lt;Node&gt; children = parent.getChildrenUnmodifiable(); for (Node child : children) { addListenerDeeply(child, listener); } } } static class ResizeListener implements EventHandler&lt;MouseEvent&gt; { private Stage stage; private Cursor cursorEvent = Cursor.DEFAULT; private int border = 4; private double startX = 0; private double startY = 0; public ResizeListener(Stage stage) { this.stage = stage; } @Override public void handle(MouseEvent mouseEvent) { EventType&lt;? extends MouseEvent&gt; mouseEventType = mouseEvent.getEventType(); Scene scene = stage.getScene(); double mouseEventX = mouseEvent.getSceneX(), mouseEventY = mouseEvent.getSceneY(), sceneWidth = scene.getWidth(), sceneHeight = scene.getHeight(); if (MouseEvent.MOUSE_MOVED.equals(mouseEventType) == true) { if (mouseEventX &lt; border &amp;&amp; mouseEventY &lt; border) { cursorEvent = Cursor.NW_RESIZE; } else if (mouseEventX &lt; border &amp;&amp; mouseEventY &gt; sceneHeight - border) { cursorEvent = Cursor.SW_RESIZE; } else if (mouseEventX &gt; sceneWidth - border &amp;&amp; mouseEventY &lt; border) { cursorEvent = Cursor.NE_RESIZE; } else if (mouseEventX &gt; sceneWidth - border &amp;&amp; mouseEventY &gt; sceneHeight - border) { cursorEvent = Cursor.SE_RESIZE; } else if (mouseEventX &lt; border) { cursorEvent = Cursor.W_RESIZE; } else if (mouseEventX &gt; sceneWidth - border) { cursorEvent = Cursor.E_RESIZE; } else if (mouseEventY &lt; border) { cursorEvent = Cursor.N_RESIZE; } else if (mouseEventY &gt; sceneHeight - border) { cursorEvent = Cursor.S_RESIZE; } else { cursorEvent = Cursor.DEFAULT; } scene.setCursor(cursorEvent); } else if(MouseEvent.MOUSE_EXITED.equals(mouseEventType) || MouseEvent.MOUSE_EXITED_TARGET.equals(mouseEventType)){ scene.setCursor(Cursor.DEFAULT); } else if (MouseEvent.MOUSE_PRESSED.equals(mouseEventType) == true) { startX = stage.getWidth() - mouseEventX; startY = stage.getHeight() - mouseEventY; } else if (MouseEvent.MOUSE_DRAGGED.equals(mouseEventType) == true) { if (Cursor.DEFAULT.equals(cursorEvent) == false) { if (Cursor.W_RESIZE.equals(cursorEvent) == false &amp;&amp; Cursor.E_RESIZE.equals(cursorEvent) == false) { double minHeight = stage.getMinHeight() &gt; (border*2) ? stage.getMinHeight() : (border*2); if (Cursor.NW_RESIZE.equals(cursorEvent) == true || Cursor.N_RESIZE.equals(cursorEvent) == true || Cursor.NE_RESIZE.equals(cursorEvent) == true) { if (stage.getHeight() &gt; minHeight || mouseEventY &lt; 0) { stage.setHeight(stage.getY() - mouseEvent.getScreenY() + stage.getHeight()); stage.setY(mouseEvent.getScreenY()); } } else { if (stage.getHeight() &gt; minHeight || mouseEventY + startY - stage.getHeight() &gt; 0) { stage.setHeight(mouseEventY + startY); } } } if (Cursor.N_RESIZE.equals(cursorEvent) == false &amp;&amp; Cursor.S_RESIZE.equals(cursorEvent) == false) { double minWidth = stage.getMinWidth() &gt; (border*2) ? stage.getMinWidth() : (border*2); if (Cursor.NW_RESIZE.equals(cursorEvent) == true || Cursor.W_RESIZE.equals(cursorEvent) == true || Cursor.SW_RESIZE.equals(cursorEvent) == true) { if (stage.getWidth() &gt; minWidth || mouseEventX &lt; 0) { stage.setWidth(stage.getX() - mouseEvent.getScreenX() + stage.getWidth()); stage.setX(mouseEvent.getScreenX()); } } else { if (stage.getWidth() &gt; minWidth || mouseEventX + startX - stage.getWidth() &gt; 0) { stage.setWidth(mouseEventX + startX); } } } } } } } } </code></pre>
45,137,555
@RefreshScope not working - Spring Boot
<p>I am following the approach described here: <a href="https://github.com/jeroenbellen/blog-manage-and-reload-spring-properties" rel="noreferrer">https://github.com/jeroenbellen/blog-manage-and-reload-spring-properties</a>, the only difference is that in my case, the properties are being used in multiple classes so I have put them all in one utility class <code>CloudConfig</code> and I refer to its variables using the getters. This is what the class looks like: </p> <pre><code>@Configuration @RefreshScope public class CloudConfig { static volatile int count; // 20 sec @Value("${config.count}") public void setCount(int count) { this.count = count; } public static int getCount() { return count; } } </code></pre> <p>and I use the variable <code>count</code> in other classes like <code>CloudConfig.getCount()</code>. I am able to load the properties on bootup just fine but I am not able to dynamically update them on the fly. Can anyone tell what I am doing wrong? If instead of making this config class, I do exactly what the tutorial describes everything works fine but I am having trouble adapting it to my usecase. Can anybody tell what I am missing?</p>
45,137,964
2
3
null
2017-07-17 06:43:51.013 UTC
9
2018-08-21 17:45:33.183 UTC
null
null
null
null
4,677,943
null
1
7
spring-boot|spring-cloud|spring-cloud-config
41,950
<p>Try using <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-typesafe-configuration-properties" rel="noreferrer">@ConfigurationProperties</a> instead. e.g.</p> <pre><code>@ConfigurationProperties(prefix="config") public class CloudConfig { private Integer count; public Integer count() { return this.count; } public void setCount(Integer count) { this.count = count; } } </code></pre> <p>The <a href="http://projects.spring.io/spring-cloud/spring-cloud.html#_refresh_scope" rel="noreferrer">reference doc from spring cloud</a> states:</p> <blockquote> <p>@RefreshScope works (technically) on an @Configuration class, but it might lead to surprising behaviour: e.g. it does not mean that all the @Beans defined in that class are themselves @RefreshScope. Specifically, anything that depends on those beans cannot rely on them being updated when a refresh is initiated, unless it is itself in @RefreshScope (in which it will be rebuilt on a refresh and its dependencies re-injected, at which point they will be re-initialized from the refreshed @Configuration).</p> </blockquote>
17,453,032
what different between InternalResourceViewResolver vs UrlBasedViewResolver
<p>I just started using Spring. I came across a lot tutorials. I saw more examples using <code>InternalResourceViewResolver</code> than <code>UrlBasedViewResolver</code>. I looked at the Spring documentation, but I can't figure out the benefit of using one or the other. Can someone provide some explanation?</p>
17,453,197
3
0
null
2013-07-03 16:12:50.333 UTC
9
2016-10-13 19:24:12.72 UTC
2013-07-03 17:33:36.91 UTC
null
1,947,286
null
2,142,023
null
1
24
java|spring
18,556
<p><a href="http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/servlet/view/InternalResourceViewResolver.html" rel="noreferrer"><code>InternalResourceViewResolver</code></a> is a convenient subclass of <a href="http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/servlet/view/UrlBasedViewResolver.html" rel="noreferrer"><code>UrlBasedViewResolver</code></a>.</p> <p>The JavaDoc describes some added properties in <code>InternalResourceViewResolver</code> that might be useful in some situations:</p> <blockquote> <p>Convenient subclass of UrlBasedViewResolver that supports <a href="http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/servlet/view/InternalResourceView.html" rel="noreferrer">InternalResourceView</a> (i.e. Servlets and JSPs) and subclasses such as JstlView.</p> </blockquote> <p><code>AlwaysInclude</code>: Controls whether either a forward or include is done.</p> <p><code>ExposeContextBeansAsAttributes</code>: Allows all beans in context to be available as request attributes, which means they can be referenced from the EL in JSP.</p> <p><code>ExposedContextBeanNames</code>: If non-null, specifies the list of beans that will be exposed, as opposed to all of them.</p> <p>Source from spring forum : <a href="http://forum.spring.io/forum/spring-projects/web/64551-internalresourceviewresolver-and-urlbasedviewresolver" rel="noreferrer">Spring Q&amp;A forum</a></p>
26,112,993
Xcode: Any way to refresh/re-run the playground?
<p>The Playground in Xcode automatically updates as you type, but I can't figure out how to get the Playground to "re-compile".</p> <p>In many cases this wouldn't matter, but if you're writing code that generates or uses random values it can be useful to run it a few times to make sure it's working. Is there any way to get the playground to reset / refresh / re-run?</p> <p>Seen a few questions asking how to stop the Playground from auto-updating, but nothing for the opposite.</p> <p>Easiest way to do this seems to be to just edit the code (add and remove a space), or put in some kind of a loop... Just wondering if there's a menu shortcut etc.</p>
26,134,774
7
2
null
2014-09-30 04:49:57.153 UTC
5
2019-11-01 12:46:49.85 UTC
2017-03-31 15:31:00.687 UTC
null
1,032,372
null
1,032,372
null
1
61
ios|swift|refresh|xcode6|swift-playground
33,500
<p>Try <code>Editor</code> > <code>Execute Playground</code> from Xcode menu</p> <p><img src="https://i.stack.imgur.com/p9HX9.png" alt="enter image description here"></p> <p>I don't know what <code>Reset Playground</code> is, by the way.</p>
26,345,407
How to connect existing Android Studio project to existing Github repository
<p>So I am new to Android development and Android Studio.</p> <p>I used Android Studio to create an Android project, and each time I wanted to commit the code to GitHub, I switched over to the command line and committed/pushed the code from there. </p> <p>However, I realize now that Android Studio has it's own features for connecting to GitHub. I'd like to use those features. </p> <p>Since the project already exists, I prefer not to just create a new GitHub repository from Android Studio and delete the old one. I just want to connect the existing GitHub repository with the Android Studio project.</p> <p>How can I sync these up?</p>
26,347,135
7
4
null
2014-10-13 17:17:27.573 UTC
12
2022-05-31 13:29:46.397 UTC
null
null
null
null
3,779,669
null
1
55
android|git|github|android-studio
108,040
<p>I would view this thread if you want to create a new project.</p> <p><a href="https://stackoverflow.com/questions/16644946/how-do-you-sync-projects-to-github-with-android-studio">How do you synchronise projects to GitHub with Android Studio?</a></p> <p>If this doesn't help then I would just delete your current(local) project and import from github.</p> <p><a href="http://teamtreehouse.com/library/android-tools/git/pulling-down-github-projects-to-android-studio" rel="nofollow noreferrer">http://teamtreehouse.com/library/android-tools/git/pulling-down-github-projects-to-android-studio</a></p> <p>I would recommend staying with command line. It is great practice. View link below for more information.</p> <p><a href="https://softwareengineering.stackexchange.com/questions/173297/why-learn-git-when-there-are-gui-apps-for-github">https://softwareengineering.stackexchange.com/questions/173297/why-learn-git-when-there-are-gui-apps-for-github</a></p>
23,090,459
IEnumerable Where() and ToList() - What do they really do?
<p>I was wondering what exactly the <code>Where()</code> and <code>ToList()</code> methods are doing. Specifically I was wondering if the <code>Where()</code> will create a new object in memory or return a new object. </p> <p>Ok, looking at the following code, say I have a skeleton log class.</p> <pre><code>public class Log() { public string Log {get;set;} public string CreatedByUserId {get;set;} public string ModifiedUserId {get;set;} } </code></pre> <p>In my business logic, say I only want logs created or modified by a certain user. This is going to be accomplished with a method: <code>FilterLogsAccordingToUserId()</code>.</p> <pre><code>public IEnumerable&lt;Log&gt; FilterLogsAccordingToUserId(IEnumerable&lt;Log&gt; logs, string userId) { int user = int.Parse(userId); return logs.Where(x =&gt; x.CreatedByUserId.Equals(user) || x.ModifiedByUserId.Equals(user)).ToList(); } </code></pre> <p>In this situation, is <code>Where()</code> modifying the <code>IEnumerable&lt;Log&gt;</code> by removing all objects that don't match the condition, or is it grabbing all objects, casting that object to a list in memory, and then return that new object?</p> <p>If it is the second possibility, am I right to be concerned about performance if a sufficiently large list of logs is passed to the function?</p>
23,090,569
4
9
null
2014-04-15 17:23:46.513 UTC
5
2017-02-21 14:04:31.62 UTC
2014-04-16 14:29:13.943 UTC
null
90,674
null
1,840,331
null
1
14
c#|.net|linq
39,435
<p>Let's take the two methods separately.</p> <h1>Where</h1> <p>This one will return a new object, that when enumerated, will filter the original collection object by the predicate.</p> <p>It will in no way change the original collection, <em>but it will be linked to it</em>.</p> <p>It is also a deferred execution collection, which means that until you actually enumerated it, and <em>every time you enumerate it</em>, it will use the original collection and filter that.</p> <p>This means that if you change the original collection, the filtered result of it will change accordingly.</p> <p>Here is a simple <a href="http://linqpad.net">LINQPad</a> program that demonstrates:</p> <pre><code>void Main() { var original = new List&lt;int&gt;(new[] { 1, 2, 3, 4 }); var filtered = original.Where(i =&gt; i &gt; 2); original.Add(5); filtered.Dump(); original.Add(6); filtered.Dump(); } </code></pre> <p>Output:</p> <p><img src="https://i.stack.imgur.com/t4AoK.png" alt="LINQPad output #1"></p> <p>As you can see, adding more elements to the original collection that satisfies the filtering conditions of the second collection will make those elements appear in the filtered collection as well.</p> <h1>ToList</h1> <p>This will create a new list object, populate it with the collection, and return that collection.</p> <p>This is an immediate method, meaning that once you have that list, it is now a completely separate list from the original collection.</p> <p>Note that the objects <em>in</em> that list may still be shared with the original collection, the <code>ToList</code> method does not make new copies of all of those, but the <em>collection</em> is a new one.</p> <p>Here is a simple <a href="http://linqpad.net">LINQPad</a> program that demonstrates:</p> <pre><code>void Main() { var original = new List&lt;int&gt;(new[] { 1, 2, 3, 4 }); var filtered = original.Where(i =&gt; i &gt; 2).ToList(); original.Add(5); original.Dump(); filtered.Dump(); } </code></pre> <p>Output:</p> <p><img src="https://i.stack.imgur.com/up3x7.png" alt="LINQPad output #2"></p> <p>Here you can see that once we've created that list, it doesn't change if the original collection changes.</p> <p>You can think of the <code>Where</code> method as being linked to the original collection, whereas <code>ToList</code> will simply return a new list with the elements and not be linked to the original collection.</p> <p>Now, let's look at your final question. Should you be worried about performance? Well, this is a rather large topic, but <em>yes</em>, you should be worried about performance, but not to such a degree that you do it all the time.</p> <p>If you give a <em>large</em> collection to a <code>Where</code> call, <em>every</em> time you enumerate the results of the <code>Where</code> call, you will enumerate the original large collection and filter it. If the filter only allows for few of those elements to pass by it, it will still enumerate over the original large collection every time you enumerate it.</p> <p>On the other hand, doing a <code>ToList</code> on something large will also create a large list.</p> <p>Is this going to be a performance problem?</p> <p>Who can tell, but for all things performance, here's my number 1 answer:</p> <ol> <li>First know that you have a problem</li> <li>Secondly measure your code using the appropriate (memory, cpu time, etc.) tool to figure out <em>where</em> the performance problem is</li> <li>Fix it</li> <li>Return to number 1</li> </ol> <p>Too often you will see programmers fret over a piece of code, thinking it will incur a performance problem, only to be dwarfed by the slow user looking at the screen wondering what to do next, or by the download time of the data, or by the time it takes to write the data to disk, or what not.</p> <p>First you know, then you fix.</p>
5,350,314
How to free a pointer to a dynamic array in C?
<p>I create a dynamic array in C with malloc, ie.:</p> <pre><code>myCharArray = (char *) malloc(16); </code></pre> <p>Now if I make a function like this and pass <code>myCharArray</code> to it:</p> <pre><code>reset(char * myCharArrayp) { free(myCharArrayp); } </code></pre> <p>will that work, or will I somehow only free the copy of the pointer to <code>myCharArrayp</code> and not the actual <code>myCharArray</code>?</p>
5,350,324
3
0
null
2011-03-18 09:52:52.07 UTC
1
2020-09-03 14:48:29.65 UTC
2020-09-03 14:48:29.65 UTC
null
3,442,409
null
259,970
null
1
5
c|pointers|free|dynamic-arrays
38,075
<p>That will be fine and free the memory as you expect.</p> <p>I would consider writing the function this way:</p> <pre><code> void reset(char** myPointer) { if (myPointer) { free(*myPointer); *myPointer = NULL; } } </code></pre> <p>so that the pointer is set to NULL after being freed. Reusing previously freed pointers is a common source of errors.</p>
5,463,547
WCF - "There was no endpoint listening at..." error
<p>I have two applications that I want to test locally on the same machine. App 1 has a simple WCF service with the folloiwng config entry:</p> <pre><code>&lt;service behaviorConfiguration="MyNamespace.ContainerManagementServiceBehavior" name="MyNamespace.ContainerManagementService"&gt; &lt;endpoint address="ContainerManagementService" binding="basicHttpBinding" name="ContainerManagementbasicHttpEndpoint" contract="MyNamespace.IContainer" /&gt; &lt;endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="http://localhost:8000/ContainerManagementService" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;/service&gt; &lt;behaviors&gt; &lt;behavior name="MyNamespace.ContainerManagementServiceBehavior"&gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;serviceDebug includeExceptionDetailInFaults="false" /&gt; &lt;/behavior&gt; &lt;/behaviors&gt; </code></pre> <p>I start the service by running the web application project where it is hosted. I am able to successfully browse to the url and get web service information page from ie. I copy the same URL and use it for my client.</p> <p>My other client, App 2, has the following in its config file:</p> <pre><code>&lt;system.serviceModel&gt; &lt;bindings&gt; &lt;basicHttpBinding&gt; &lt;binding name="basicHttp" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="5242880" maxBufferPoolSize="524288" maxReceivedMessageSize="5242880" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"&gt; &lt;readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="5242880" /&gt; &lt;security mode="None"&gt; &lt;transport clientCredentialType="None" proxyCredentialType="None" realm="" /&gt; &lt;message clientCredentialType="UserName" algorithmSuite="Default" /&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/basicHttpBinding&gt; &lt;/bindings&gt; &lt;client&gt; &lt;endpoint address="http://localhost:3227/Services/ContainerManagementService.svc" binding="basicHttpBinding" bindingConfiguration="basicHttp" contract="MyService.IService" name="externalService" /&gt; &lt;/client&gt; &lt;/system.serviceModel&gt; </code></pre> <p>However, when I try to execute a WCF call form client to the running service, I get the following error message:</p> <pre><code>There was no endpoint listening at http://localhost:3227/Services/ContainerManagementService.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details. </code></pre> <p>What could be happening? </p>
5,477,332
3
0
null
2011-03-28 18:42:28.5 UTC
null
2013-05-13 08:50:00.82 UTC
2013-05-13 08:50:00.82 UTC
null
57,428
null
29,726
null
1
8
wcf
58,565
<p>It looks likes the issue is due to the fact that both server and client are being run from the Cassini server. I am changing the architecture to host the server endpoint in IIS.</p>
9,145,321
Implementing a User-Level Threads Package
<p>I have been tasked in a class to create a user level thread library in C. I was wondering if anyone could give me a list of things to read up on to accomplish this. I have a good idea as to where to start, but any resources on user level threads and some applicable aspects of the C language that might help would be extremely valuable.</p> <p>I am very unclear as to how I would implement a scheduler for such. Assume that I have a pretty good understanding of the C language and some of its more helpful library functions.</p>
9,145,850
3
4
null
2012-02-04 22:48:26.243 UTC
9
2014-10-28 18:55:39.25 UTC
2012-09-18 03:01:59.983 UTC
null
1,288
null
832,271
null
1
19
c|multithreading
9,695
<p>I’ve done this for a homework assignment without writing any assembler at all. The thread switch mechanism was <code>setjmp</code>/<code>longjmp</code>. What this involved was allocating memory for each thread’s stack, then very carefully massaging the values in the <code>jmp_buff</code> so execution jumps to the next thread’s stack.</p> <p>See also Russ Cox’s pretty readable <a href="http://swtch.com/libtask/">libtask</a>.</p> <p>Edit in response to OP’s comment: In deciding when to switch threads there are two main directions: preemptive &amp; cooperative. In the preemptive model, you’ll have something like a timer signal that causes execution flow to jump to a central dispatcher thread, which chooses the next thread to run. In a cooperative model, threads “yield” to each other, either explicitly (<em>e.g.</em>, by calling a <code>yield()</code> function you’ll provide) or implicitly (<em>e.g.</em>, requesting a lock held by another thread).</p> <p>Take a look at the API of libtask for an example of the cooperative model, particularly the description of the function <code>taskyield()</code>. That’s the explicit yield I mentioned. There are also the non-blocking I/O functions which include an implicit yield—the current “task” is put on hold until the I/O completes, but the other tasks get their chance to run.</p>
9,377,237
How can I define ENTER keypressed event for a dynamically chosen Cell in VBA for Excel
<p>I got a dynamically chosen Cell that will be filled with some information that im going to put and when I put the information and <strong><kbd>ENTER</kbd> keypressed</strong> at that Cell;</p> <p><strong>1 - it should trigger a macro</strong></p> <pre><code>'macro(value) macro1 myinfo </code></pre> <p><strong>2 - macro should get the info in that cell</strong></p> <pre><code>myinfo = Cells( i, j ) </code></pre> <p>So how can i achive that?</p>
9,378,989
4
5
null
2012-02-21 12:00:30.17 UTC
6
2016-05-12 15:12:30.137 UTC
2012-02-21 14:12:32.953 UTC
null
78,522
null
861,019
null
1
10
events|vba|excel
93,061
<p>To capture a specific key being pressed, you need the <code>OnKey</code> method:</p> <pre><code>Application.OnKey "~", "myMacro" ' for the regular enter key ' or if you want Enter from the numeric keypad: ' Application.OnKey "{ENTER}", "myMacro" ' Below I'll just assume you want the latter. </code></pre> <p>The above says that <code>myMacro</code> must be run when the <kbd>Enter</kbd> key is pressed. The <code>OnKey</code> method only needs to be called once. You could put it in the <code>Workbook_Open</code> event:</p> <pre><code>Private Sub Workbook_Open() Application.OnKey "{ENTER}", "myMacro" End Sub </code></pre> <p>To stop capturing the <kbd>Enter</kbd> key, </p> <pre><code>Application.OnKey "{ENTER}" </code></pre> <hr> <p>To check whether <kbd>Enter</kbd> was pressed while on cell A1, you could do this:</p> <pre><code>Sub myMacro() If Not Intersect(Selection, Range("A1")) Is Nothing Then ' equivalent to but more flexible and robust than 'If Selection.Address = "$A$1" Then MsgBox "You pressed Enter while on cell A1." End If End Sub </code></pre> <hr> <p>Now to detect if <kbd>Enter</kbd> was pressed in a specific cell <em>only if that cell has been edited</em>, we have to be a bit clever. Let's say you edit a cell value and press Enter. The first thing that is triggered is the <code>OnKey</code> macro, and after that the <code>Worksheet_Change</code> event is triggered. So you first have to "save the results" of <code>OnKey</code>, and then handle the <code>Worksheet_Change</code> event based on those results.</p> <p>Initiate <code>OnKey</code> like this: <code>Application.OnKey "{ENTER}", "recordEnterKeypress"</code></p> <p>In your code module you would have this:</p> <pre><code>Public enterWasPressed As Boolean Sub recordEnterKeypress() enterWasPressed = True End Sub </code></pre> <p>The cell edit will be captured by the <code>Worksheet_Change</code> event:</p> <pre><code>Private Sub Worksheet_Change(ByVal Target As Range) If enterWasPressed _ And Not Intersect(Target, Range("A1")) Is Nothing Then MsgBox "You just modified cell A1 and pressed Enter." End If enterWasPressed = False 'reset it End Sub </code></pre> <hr> <p>Now, the above code does what you ask in the question, but I would like to reiterate: your question sounds awfully like an <a href="http://www.perlmonks.org/index.pl?node_id=542341" rel="noreferrer">XY problem</a>. Why do you want to detect the <kbd>Enter</kbd> key being pressed? Let us know and maybe we can suggest alternatives.</p>
18,592,173
Select objects based on value of variable in object using jq
<p>I have the following json file:</p> <pre><code>{ &quot;FOO&quot;: { &quot;name&quot;: &quot;Donald&quot;, &quot;location&quot;: &quot;Stockholm&quot; }, &quot;BAR&quot;: { &quot;name&quot;: &quot;Walt&quot;, &quot;location&quot;: &quot;Stockholm&quot; }, &quot;BAZ&quot;: { &quot;name&quot;: &quot;Jack&quot;, &quot;location&quot;: &quot;Whereever&quot; } } </code></pre> <p>I am using jq and want to get the &quot;name&quot; elements of the objects where 'location' is 'Stockholm'.</p> <p>I know I can get all names by</p> <pre><code>cat json | jq .[] | jq .&quot;name&quot; &quot;Jack&quot; &quot;Walt&quot; &quot;Donald&quot; </code></pre> <p>But I can't figure out how to print only certain objects, given the value of a sub key (here: <code>&quot;location&quot; : &quot;Stockholm&quot;</code>).</p>
18,608,100
4
0
null
2013-09-03 12:19:32.12 UTC
80
2022-02-01 08:23:06.63 UTC
2021-03-27 10:32:56.143 UTC
null
963,881
null
179,444
null
1
400
json|bash|select|jq
471,727
<p>Adapted from this post on <a href="https://zerokspot.com/weblog/2013/07/18/processing-json-with-jq/" rel="noreferrer">Processing JSON with jq</a>, you can use the <a href="https://stedolan.github.io/jq/manual/#select(boolean_expression)" rel="noreferrer"><code>select(bool)</code></a> like this:</p> <pre class="lang-sh prettyprint-override"><code>$ jq '.[] | select(.location=="Stockholm")' json { "location": "Stockholm", "name": "Walt" } { "location": "Stockholm", "name": "Donald" } </code></pre>
15,413,434
TypedQuery instead of normal Query in JPA
<p>Is it possible to write this Query as a TypedQuery and let the two Long's run into a Object with two public Long fields inside.</p> <pre><code> Query q = em.createQuery( "SELECT c.id, COUNT(t.id) " + "FROM PubText t " + "JOIN t.comm c " + "WHERE c.element = ?1 " + "GROUP BY c.id"); q.setParameter(1, e); List&lt;?&gt; rl = q.getResultList(); Iterator&lt;?&gt; it = rl.iterator(); HashMap&lt;Long, Long&gt; res = new HashMap&lt;Long, Long&gt;(); while (it.hasNext()) { Object[] n = (Object[]) it.next(); res.put((Long)n[0], (Long)n[1]); } return res; </code></pre>
15,413,536
2
0
null
2013-03-14 15:28:25.2 UTC
5
2015-02-04 05:50:22.007 UTC
null
null
null
null
1,033,919
null
1
13
jakarta-ee|jpa|glassfish-3|jpql
38,631
<p>JPA has a feature just for this - constructor expressions:</p> <pre><code>Query q = entityManager.createQuery("SELECT NEW com.example.DTO( c.id, COUNT(t.id)) FROM ..."); List&lt;DTO&gt; dtos = q.getResultList(); </code></pre> <p>Your DTO class can be a POJO. All it will need is a public constructor accepting 2 <code>Long</code>s. Please note that you have to provide a fully qualified name of your class after the <code>NEW</code>operator.</p>
15,374,191
How to set animated icon to QPushButton in Qt5?
<p><code>QPushButton</code> can have icon, but I need to set animated icon to it. How to do this? I created new class implemented from <code>QPushButton</code> but how to replace icon from <code>QIcon</code> to <code>QMovie</code>?</p>
65,310,798
2
0
null
2013-03-12 23:22:17.013 UTC
9
2020-12-15 17:30:30.91 UTC
2015-12-10 20:52:16.383 UTC
null
4,904,417
null
747,709
null
1
21
qt|animation|icons|qt5|qpushbutton
13,409
<p>Since I had to solve this problem for a project of mine today, I just wanted to drop the solution I found for future people, because this question has lots of views and I considered the solution quite elegant. The solution was posted <a href="https://forum.qt.io/topic/93659/how-to-apply-gif-to-qpushbutton/3" rel="nofollow noreferrer">here</a>. It sets the icon of the pushButton every time, the frame of the QMovie changes:</p> <pre><code>auto movie = new QMovie(this); movie-&gt;setFileName(&quot;:/sample.gif&quot;); connect(movie, &amp;QMovie::frameChanged, [=]{ pushButton-&gt;setIcon(movie-&gt;currentPixmap()); }); movie-&gt;start(); </code></pre> <p>This also has the advantage, that the icon will not appear, until the QMovie was started. Here is also the python solution, I derived for my project:</p> <pre><code>#'hide' the icon on the pushButton pushButton.setIcon(QIcon()) animated_spinner = QtGui.QMovie(&quot;:/icons/images/loader.gif&quot;) animated_spinner.frameChanged.connect(updateSpinnerAniamation) def updateSpinnerAniamation(self): #'hide' the text of the button pushButton.setText(&quot;&quot;) pushButton.setIcon(QtGui.QIcon(animated_spinner.currentPixmap())) </code></pre> <p>Once you want to show the spinner, just start the QMovie:</p> <pre><code>animated_spinner.start() </code></pre> <p>If the spinner should disappear again, then stop the animation and 'hide' the spinner again. Once the animation is stopped, the frameChanged slot won't update the button anymore.</p> <pre><code>animated_spinner.stop() pushButton.setIcon(QtGui.QIcon()) </code></pre>
15,281,036
How to run Ruby 2.0 with JRuby 1.7?
<p>What is the best way to get JRuby to run in 2.0 mode? </p>
15,281,071
1
0
null
2013-03-07 20:25:13.67 UTC
6
2013-03-07 20:27:14.307 UTC
null
null
null
null
289,466
null
1
28
ruby|jruby|ruby-2.0
9,136
<p>For a specific script, you can use the <code>--2.0</code> option:</p> <pre><code>jruby --2.0 -S rails s </code></pre> <p>For setting 2.0 as the default value, set <code>JRUBY_OPTS</code>:</p> <pre><code>export JRUBY_OPTS=--2.0 </code></pre> <p>You can also set the value in <code>~/.jrubyrc</code>:</p> <pre><code>compat.version=2.0 </code></pre>
15,199,119
Runtime.exec().waitFor() doesn't wait until process is done
<p>I have this code:</p> <pre><code>File file = new File(path + "\\RunFromCode.bat"); file.createNewFile(); PrintWriter writer = new PrintWriter(file, "UTF-8"); for (int i = 0; i &lt;= MAX; i++) { writer.println("@cd " + i); writer.println(NATIVE SYSTEM COMMANDS); // more things } writer.close(); Process p = Runtime.getRuntime().exec("cmd /c start " + path + "\\RunFromCode.bat"); p.waitFor(); file.delete(); </code></pre> <p>What happens is that the file deleted before it actually executed.</p> <p>Is this because the <code>.bat</code> file contains only native system call? How can I make the deletion <strong>after</strong> the execution of the <code>.bat</code> file? (I don't know what the output of the <code>.bat</code> file will be, since it dynamically changes).</p>
15,199,167
4
2
null
2013-03-04 10:12:55.723 UTC
9
2017-02-27 15:09:07.237 UTC
2016-02-27 09:08:29.633 UTC
null
1,735,406
null
1,735,406
null
1
37
java|runtime.exec
82,715
<p>By using <code>start</code>, you are asking<code>cmd.exe</code> to start the batch file in the background:</p> <pre><code>Process p = Runtime.getRuntime().exec("cmd /c start " + path + "\\RunFromCode.bat"); </code></pre> <p>So, the process which you launch from Java (<code>cmd.exe</code>) returns before the background process is finished.</p> <p>Remove the <code>start</code> command to run the batch file in the foreground - then, <code>waitFor()</code> will wait for the batch file completion:</p> <pre><code>Process p = Runtime.getRuntime().exec("cmd /c " + path + "\\RunFromCode.bat"); </code></pre> <hr> <p>According to OP, it is important to have the console window available - this can be done by adding the <code>/wait</code> parameter, as suggested by @Noofiz. The following SSCCE worked for me:</p> <pre><code>public class Command { public static void main(String[] args) throws java.io.IOException, InterruptedException { String path = "C:\\Users\\andreas"; Process p = Runtime.getRuntime().exec("cmd /c start /wait " + path + "\\RunFromCode.bat"); System.out.println("Waiting for batch file ..."); p.waitFor(); System.out.println("Batch file done."); } } </code></pre> <p>If <code>RunFromCode.bat</code> executes the <code>EXIT</code> command, the command window is automatically closed. Otherwise, the command window remains open until you explicitly exit it with <code>EXIT</code> - the java process is waiting until the window is closed in either case.</p>
8,250,153
Set and get a static variable from two different classes in Java
<p>Lets say I have 3 Classes: <code>A</code>, <code>Data</code>, and <code>B</code></p> <p>I pass a variable from class <code>A</code> which sets that passed variable to a private variable in class <code>Data</code>.</p> <p>Then in class <code>B</code>, I want to call that specific variable which has been changed.</p> <p>So I do</p> <pre><code>Data data = new Data(); data.getVariable(); </code></pre> <p>It will then return null, since in class <code>Data</code> I initialize variables to nothing (ex: <code>int v;</code>), and I think that class <code>B</code> is initializing a brand new class and resetting the values to default, but I don't know how to fix this.</p> <p>I know that the variable is setting properly because in class <code>A</code> if I do <code>data.getVariable()</code> it will print the variable that was set.</p> <p>Class <code>A</code>:</p> <pre><code>Data data = new Data(); int d = 1; data.setVariable(d); </code></pre> <p>Class <code>Data</code>:</p> <pre><code>private static int b; public void setVariable(int s) { b = s; } public int getVariable() { return b; } </code></pre> <p>Class <code>B</code>:</p> <pre><code>Data data = new Data(); private int v; v = data.getVariable(); System.out.println(v); </code></pre> <p>This will print out 0 instead of the actual value</p>
8,250,692
2
10
null
2011-11-23 22:49:34.837 UTC
1
2013-01-17 20:19:11.81 UTC
2011-11-23 23:45:39.31 UTC
null
900,873
null
1,062,898
null
1
5
java|class|variables|methods|overwrite
40,398
<p>When you instantiate a <code>Data</code> object in class A, and instantiate another <code>Data</code> object in class B, they are <em>two different instances</em> of the <code>Data</code> class. They both instantiate <code>d</code> to 0 by default. You then call <code>setVariable</code> on the instance in class A and pass it the value of 1; but the instance in class B remains in 0. In order to change the value of the instance in class B, you would need to call <code>setVariable</code> on the instance in class B.</p> <p>What it seems like you're looking for is a static member. Static members are the same across all instances of the same class. Just put the <code>static</code> keyword before the method(s) or field(s) that you want to use it. Static members and fields are typically accessed using the name of the class in which they are declared (i.e. <code>MyClass.doMethod()</code>). For example:</p> <p><strong>Class Data (updated):</strong></p> <pre><code>private static int b; public static void setVariable(int s) { b = s; } public static int getVariable() { return b; } </code></pre> <p><strong>Class A</strong>:</p> <pre><code>Data.setVariable(d); </code></pre> <p><strong>Class B</strong>:</p> <pre><code>v = Data.getVariable(); System.out.println(v); </code></pre>
9,220,171
Setting Oracle size of row fetches higher makes my app slower?
<p>As detailed <a href="http://webmoli.com/2009/02/01/jdbc-performance-tuning-with-optimal-fetch-size/">here</a> and confirmed <a href="http://docs.oracle.com/cd/B13789_01/java.101/b10979/basic.htm#g1028323">here</a>, the default number of rows Oracle returns at time when querying for data over JDBC is 10. I am working on an app that to has to read and compare lots of data from our database. I thought that if we just increase <code>defaultRowPrefetch</code> to be something like 1000, then surely our app would perform faster. As it turned out, it <strong>performed slower</strong> and by about 20%. </p> <p>We then decided to just slowly increase the number from 10 and see how it performs. We've seen about a 10% increase by setting it somewhere between 100 and 200. I would have never guessed, however, that setting it higher would make our app perform more slowly. Any ideas why this might happen?</p> <p>Thanks!</p> <p><strong>EDIT:</strong></p> <p>Just for clarification, I'm using Oracle 11g R2 and Java 6.</p> <p><strong>EDIT 2:</strong></p> <p>Okay, I wanna restate my question to be clear, because judging from the answers below, I am not expressing myself properly: </p> <blockquote> <p>How is it possible that if I set a higher fetch size, my app performs slower? To me, that sounds like saying "We're giving you a faster internet connection, i.e. a fatter pipe, but your web browsing will be slower.</p> </blockquote> <p>All other things being equal, as they have been in our tests, we're super curious about how our app could perform worse with only this one change.</p>
9,317,858
6
12
null
2012-02-09 22:51:49.59 UTC
17
2014-10-03 09:42:25.94 UTC
2012-02-15 20:45:27.037 UTC
null
99,971
null
99,971
null
1
30
java|performance|oracle|jdbc|oracle11g
32,266
<p>Possible explanations:</p> <ol> <li><p>Java is doing nothing, while Oracle is computing the <strong>first 1000 rows</strong> instead of first 10.</p></li> <li><p>Oracle is doing nothing, while Java is computing the <strong>last 1000 rows</strong> instead of last 10.</p></li> <li><p>Communication protocols (e.g. TCP/IP) wait a lot and then must handle more data at once, but the <strong>peak data transfer will be throttled down by hardware limits</strong>. This is countered by protocol's overhead, so there should be optimal fetch size and anything less or more would be slower ;))</p></li> <li><p>It would get worse if the process of fetching is synchronous with other Java code, so that <strong>Java asks for more rows only after processing the previous data</strong> and Oracle does nothing in the mean time.</p> <blockquote> <p>Imagine there are 3 people:</p> <ul> <li>1st one folds A4 paper in half</li> <li>2nd one brings stacks of folded paper from one room to another</li> <li>3rd cuts some shape from the folded paper.</li> </ul> <p>How big should the stacks be, if the 1st one has to wait until the 2nd one returns and the 2nd one has to wait until the 3rd one finishes their job?</p> <p>Stacks of 1000 will not be better than stacks of 10 i guess ;))</p> </blockquote></li> </ol>
8,587,531
Improving the speed of FFT Implementation
<p>I'm a beginner in programming and am currently trying to work on a project requiring Fast Fourier Transform implementation.</p> <p>I have so far managed to implement the following:</p> <p>Does anyone have any alternatives and suggestions to improve the speed of the program without losing out on accuracy.</p> <pre><code>short FFTMethod::FFTcalc(short int dir,long m,double *x,double *y) { long n,i,i1,j,k,i2,l,l1,l2; double c1,c2,tx,ty,t1,t2,u1,u2,z; /* Calculate the number of points */ n = 1; for (i=0;i&lt;m;i++) n *= 2; /* Do the bit reversal */ i2 = n &gt;&gt; 1; j = 0; for (i=0;i&lt;n-1;i++) { if (i &lt; j) { tx = x[i]; ty = y[i]; x[i] = x[j]; y[i] = y[j]; x[j] = tx; y[j] = ty; } k = i2; while (k &lt;= j) { j -= k; k &gt;&gt;= 1; } j += k; } /* Compute the FFT */ c1 = -1.0; c2 = 0.0; l2 = 1; for (l=0;l&lt;m;l++) { l1 = l2; l2 &lt;&lt;= 1; u1 = 1.0; u2 = 0.0; for (j=0;j&lt;l1;j++) { for (i=j;i&lt;n;i+=l2) { i1 = i + l1; t1 = u1 * x[i1] - u2 * y[i1]; t2 = u1 * y[i1] + u2 * x[i1]; x[i1] = x[i] - t1; y[i1] = y[i] - t2; x[i] += t1; y[i] += t2; } z = u1 * c1 - u2 * c2; u2 = u1 * c2 + u2 * c1; u1 = z; } c2 = sqrt((1.0 - c1) / 2.0); if (dir == 1) c2 = -c2; c1 = sqrt((1.0 + c1) / 2.0); } /* Scaling for forward transform */ if (dir == 1) { for (i=0;i&lt;n;i++) { x[i] /= n; y[i] /= n; } } return(1); } </code></pre>
8,591,152
4
5
null
2011-12-21 09:24:49.783 UTC
11
2012-07-27 14:15:18.533 UTC
2011-12-21 14:23:44.763 UTC
null
303,612
null
1,099,435
null
1
12
c++|fft
9,786
<p>I recently found this excellent PDF on the <a href="http://edp.org/work/Construction.pdf" rel="noreferrer">Construction of a high performance FFTs</a> by Eric Postpischil. Having developed several FFTs myself I know how hard it is to compete with commercial libraries. Believe me you're doing well if your FFT is only 4x slower than Intel or FFTW, not 40x! You can however compete, and here's how. </p> <p>To summarise that article, the author states that Radix2 FFTs are simple but inefficient, the most efficient construct is the radix4 FFT. An even more efficient method is the Radix8 however this often does not fit into the registers on a CPU so Radix4 is preferred. </p> <p>FFTs can be constructed in stages, so to compute a 1024 point FFT you could perform 10 stages of the Radix2 FFT (as 2^10 - 1024), or 5 stages of the Radix4 FFT (4^5 = 1024). You could even compute a 1024 point FFT in stages of 8*4*4*4*2 if you so choose. Fewer stages means fewer reads and writes to memory (the bottleneck for FFT performance is memory bandwidth) hence dynamically choosing radix 4, 8 or higher is a must. The Radix4 stage is particulary efficient as all weights are 1+0i, 0+1i, -1+0i, 0-1i and Radix4 butterfly code can be written to fit entirely in the cache. </p> <p>Secondly, each stage in the FFT is not the same. The first stage the weights are all equal to 1+0i. there is no point computing this weight and even multiplying by it as it is a complex multiply by 1, so the first stage may be performed without weights. The final stage may also be treated differently and can be used to perform the Decimation in Time (bit reversal). Eric Postpischil's document covers all this. </p> <p>The weights may be precomputed and stored in a table. Sin/cos calculations take around 100-150 cycles each on x86 hardware so precomputing these can save 10-20% of the overall compute time as memory access is in this case faster than CPU calculations. Using fast algorithms to compute sincos in one go is particularly beneficial (Note that cos is equal to sqrt(1.0 - sine*sine), or using table lookups, cos is just a phase shift of sine). </p> <p>Finally once you have your super streamlined FFT implementation you can utilise SIMD vectorization to compute 4x floating point or 2x double floating point operations per cycle inside the butterfly routine for another 100-300% speed improvement. Taking all of the above you'd have yourself a pretty slick and fast FFT!</p> <p>To go further you can perform optimisation on the fly by providing different implementations of the FFT stages targeted to specific processor architectures. Cache size, register count, SSE/SSE2/3/4 instruction sets etc differ per machine so choosing a one size fits all approach is often beaten by targeted routines. In FFTW for instance many smaller size FFTs are highly optimised unrolled (no loops) implementations targeted for a specific architecture. By combining these smaller constructs (such as RadixN routines) you can choose the fastest and best routine for the task at hand. </p>
8,519,943
Class 'Room' is abstract; cannot be instantiated
<p>I have an abstract class <code>Room</code> which has subclasses <code>Family</code> and <code>Standard</code>.</p> <p>I have created <code>room = new ArrayList&lt;Room&gt;();</code> within a <code>Hostel</code> class and a method to add a room to the ArrayList;</p> <pre><code>public String addRoom(String roomNumber, boolean ensuite) { if (roomNumber.equals(&quot;&quot;)) return &quot;Error - Empty name field\n&quot;; else room.add( new Room(roomNumber,ensuite) ); return &quot;RoomNumber: &quot; + roomNumber + &quot; Ensuite: &quot; + ensuite + &quot; Has been added to Hostel &quot; + hostelName; } </code></pre> <p>However I get the following compile time error;</p> <blockquote> <p>Room is abstract; cannot be instantiated</p> </blockquote> <p>I understand that abstract classes cannot be instantiated, but what is the best way to add a room?</p>
8,519,973
3
5
null
2011-12-15 12:11:55.217 UTC
1
2022-09-16 14:54:31.123 UTC
2022-09-16 14:54:31.123 UTC
null
10,749,567
null
711,170
null
1
18
java|abstract-class|instantiation
66,041
<p>You have this error because you are trying to create an instance of abstract class, which is impossible. You have to </p> <pre><code>room.add(new Family(roomNumber, ensuoute)); </code></pre> <p>or</p> <pre><code>room.add(new Standard(roomNumber, ensuoute)); </code></pre>
5,121,027
Fatal error: Call to a member function fetch_assoc() on a non-object
<p>I'm trying to execute a few queries to get a page of information about some images. I've written a function</p> <pre><code>function get_recent_highs($view_deleted_images=false) { $lower = $this-&gt;database-&gt;conn-&gt;real_escape_string($this-&gt;page_size * ($this-&gt;page_number - 1)); $query = "SELECT image_id, date_uploaded FROM `images` ORDER BY ((SELECT SUM( image_id=`images`.image_id ) FROM `image_votes` AS score) / (SELECT DATEDIFF( NOW( ) , date_uploaded ) AS diff)) DESC LIMIT " . $this-&gt;page_size . " OFFSET $lower"; //move to database class $result = $this-&gt;database-&gt;query($query); $page = array(); while($row = $result-&gt;fetch_assoc()) { try { array_push($page, new Image($row['image_id'], $view_deleted_images)); } catch(ImageNotFoundException $e) { throw $e; } } return $page; } </code></pre> <p>that selects a page of these images based on their popularity. I've written a <code>Database</code> class that handles interactions with the database and an <code>Image</code> class that holds information about an image. When I attempt to run this I get an error.</p> <pre><code>Fatal error: Call to a member function fetch_assoc() on a non-object </code></pre> <p><code>$result</code> is a mysqli resultset, so I'm baffled as to why this isn't working.</p>
5,121,044
4
1
null
2011-02-25 18:18:04.3 UTC
3
2019-11-05 03:36:02.24 UTC
2019-11-04 19:50:38.857 UTC
null
1,839,439
null
504,044
null
1
32
php|mysqli
159,844
<p>That's because there was an error in your query. <a href="http://us3.php.net/manual/en/mysqli.query.php" rel="noreferrer"><code>MySQli-&gt;query()</code></a> will return false on error. Change it to something like::</p> <pre><code>$result = $this-&gt;database-&gt;query($query); if (!$result) { throw new Exception("Database Error [{$this-&gt;database-&gt;errno}] {$this-&gt;database-&gt;error}"); } </code></pre> <p>That should throw an exception if there's an error...</p>
5,496,976
How do I set an Android ProgressBar's Size programmatically?
<p>I have a custom view that extends <code>ViewGroup</code>. It includes a <code>ProgressBar</code> and a <code>WebView</code>. I'm displaying the <code>ProgressBar</code> while the <code>WebView</code> is loading.</p> <p>This works, but the <code>ProgressBar</code> is too big. How do I make it smaller?</p> <p>Below is my non-working code:</p> <pre><code>webView = new WebView(context); webView.setWebViewClient(new MyWebChromeClient()); webView.loadUrl("file://" + path); addView(webView); progressBar = new ProgressBar(mContext, null, android.R.attr.progressBarStyleSmall); LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); progressBar.setLayoutParams(params); addView(progressBar); </code></pre>
5,497,408
7
0
null
2011-03-31 08:16:52.267 UTC
3
2020-01-04 06:13:05.837 UTC
2011-11-09 19:59:24.303 UTC
null
44
null
383,351
null
1
19
android|progress-bar
66,824
<p>You can use LayoutParams to change width and height to whatever you want.</p> <pre><code>ProgressBar progressBar = new ProgressBar(teste.this, null, android.R.attr.progressBarStyleHorizontal); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(300, 10); progressBar.setLayoutParams(params ); LinearLayout test = new LinearLayout(getApplicationContext()); test.addView(progressBar); setContentView(test); </code></pre> <p>Also when you add a view, you can use this code: <code>test.addView(progressBar,50,50);</code> where the first parameter is width and the second is height.</p>
5,346,601
Stored Procedures and ORM's
<p>What's the purpose of stored procedures compared to the use of an ORM (nHibernate, EF, etc) to handle some CRUD operations? To call the stored procedure, we're just passing a few parameters and with an ORM we send the entire SQL query, but is it just a matter of performance and security or are there more advantages?</p> <p>I'm asking this because I've never used stored procedures (I just write all SQL statements with an ORM and execute them), and a customer told me that I'll have to work with stored procedures in my next project, I'm trying to figure out when to use them.</p>
5,346,660
7
0
null
2011-03-17 23:41:02.007 UTC
13
2020-11-10 11:01:52.777 UTC
2018-10-02 18:43:11.043 UTC
null
3,739,391
null
365,383
null
1
36
stored-procedures
27,352
<p>Stored Procedures are often written in a dialect of SQL (T-SQL for SQL Server, PL-SQL Oracle, and so on). That's because they add extra capabilities to SQL to make it more powerful. On the other hand, you have a ORM, let say NH that generates SQL.</p> <p>the SQL statements generated by the ORM doesn't have the same speed or power of writing T-SQL Stored Procedures. Here is where the dilemma enters: Do I need super fast application tied to a SQL Database vendor, hard to maintain or Do I need to be flexible because I need to target to multiple databases and I prefer cutting development time by writing HQL queries than SQL ones?</p> <p>Stored Procedure are faster than SQL statements because they are pre-compiled in the Database Engine, with execution plans cached. You can't do that in NH, but you have other alternatives, like using Cache Level 1 or 2.</p> <p>Also, try to do bulk operations with NH. Stored Procedures works very well in those cases. You need to consider that SP talks to the database in a deeper level.</p> <p>The choice may not be that obvious because all depends of the scenario you are working on. </p>
5,315,539
Iterate in reverse through an array with PHP - SPL solution?
<p>Is there an SPL Reverse array iterator in PHP? And if not, what would be the best way to achieve it?</p> <p>I could simply do</p> <pre><code>$array = array_reverse($array); foreach($array as $currentElement) {} </code></pre> <p>or</p> <pre><code>for($i = count($array) - 1; $i &gt;= 0; $i--) { } </code></pre> <p>But is there a more elegant way?</p>
5,315,983
11
3
null
2011-03-15 17:25:33.813 UTC
7
2020-11-04 09:35:14.013 UTC
null
null
null
null
9,535
null
1
32
php|reverse|loops|spl
36,116
<p>There is no <code>ReverseArrayIterator</code> to do that. You can do</p> <pre><code>$reverted = new ArrayIterator(array_reverse($data)); </code></pre> <p>or make that into your own custom iterator, e.g.</p> <pre><code>class ReverseArrayIterator extends ArrayIterator { public function __construct(array $array) { parent::__construct(array_reverse($array)); } } </code></pre> <p>A slightly longer implementation that doesn't use <code>array_reverse</code> but iterates the array via the standard array functions would be</p> <pre><code>class ReverseArrayIterator implements Iterator { private $array; public function __construct(array $array) { $this-&gt;array = $array; } public function current() { return current($this-&gt;array); } public function next() { return prev($this-&gt;array); } public function key() { return key($this-&gt;array); } public function valid() { return key($this-&gt;array) !== null; } public function rewind() { end($this-&gt;array); } } </code></pre>
41,245,783
Angular testing router params breaks test bed
<p>When I provide params to my <code>TestComponent</code> the test bed blows up if the html contains a <code>[routerLink]</code></p> <p><strong>testbed setup</strong></p> <pre><code>TestBed.configureTestingModule({ imports: [SharedModule.forRoot(), ManagementModule, HttpModule, RouterModule.forRoot([{ path: '', component: TestComponent }])], declarations: [TestComponent], providers: [ BaseRequestOptions, MockBackend, { provide: Http, useFactory: function (backend: MockBackend, defaultOptions: BaseRequestOptions) { return new Http(backend, defaultOptions); }, deps: [MockBackend, BaseRequestOptions] }, { provide: APP_BASE_HREF, useValue: '/' }, { provide: ActivatedRoute, useValue: { params: Observable.of({ versionId: '1' }), parent: { params: Observable.of({ uniqueId: '1234' }) } } } ] }); TestBed.compileComponents(); }); </code></pre> <p><strong>Error logged</strong></p> <pre><code>Failed: Error in ./DetailComponent class DetailComponent - inline template:72:20 caused by: Cannot read property '_lastPathIndex' of undefined TypeError: Cannot read property '_lastPathIndex' of undefined at findStartingPosition (webpack:///home/developer/Projects/project/~/@angular/router/src/create_url_tree.js:184:0 &lt;- src/test.ts:100429:23) at createUrlTree (webpack:///home/developer/Projects/project/~/@angular/router/src/create_url_tree.js:27:21 &lt;- src/test.ts:100272:45) at Router.createUrlTree (webpack:///home/developer/Projects/project/~/@angular/router/src/router.js:424:0 &lt;- src/test.ts:28688:111) at RouterLinkWithHref.get [as urlTree] (webpack:///home/developer/Projects/project/~/@angular/router/src/directives/router_link.js:253:0 &lt;- src/test.ts:50778:32) at RouterLinkWithHref.updateTargetUrlAndHref (webpack:///home/developer/Projects/project/~/@angular/router/src/directives/router_link.js:246:0 &lt;- src/test.ts:50771:91) at RouterLinkWithHref.ngOnChanges (webpack:///home/developer/Projects/project/~/@angular/router/src/directives/router_link.js:217:67 &lt;- src/test.ts:50742:74) at Wrapper_RouterLinkWithHref.ngDoCheck (/RouterModule/RouterLinkWithHref/wrapper.ngfactory.js:101:18) at DebugAppView.View_DetailComponent3.detectChangesInternal (/ManagementModule/DetailComponent/component.ngfactory.js:548:33) at DebugAppView.AppView.detectChanges (webpack:///home/developer/Projects/project/~/@angular/core/src/linker/view.js:425:0 &lt;- src/test.ts:95635:14) at DebugAppView.detectChanges (webpack:///home/developer/Projects/project/~/@angular/core/src/linker/view.js:620:0 &lt;- src/test.ts:95830:44) at ViewContainer.detectChangesInNestedViews (webpack:///home/developer/Projects/project/~/@angular/core/src/linker/view_container.js:67:0 &lt;- src/test.ts:95967:37) at DebugAppView.View_DetailComponent0.detectChangesInternal (/ManagementModule/DetailComponent/component.ngfactory.js:85:14) at DebugAppView.AppView.detectChanges (webpack:///home/developer/Projects/project/~/@angular/core/src/linker/view.js:425:0 &lt;- src/test.ts:95635:14) at DebugAppView.detectChanges (webpack:///home/developer/Projects/project/~/@angular/core/src/linker/view.js:620:0 &lt;- src/test.ts:95830:44) </code></pre> <p><strong>template line 72</strong></p> <pre><code>&lt;a class="button" [routerLink]="['/']"&gt;Back&lt;/a&gt; </code></pre> <p>In an ideal world i'd like to continue providing the params, any idea why its blowing up?</p>
41,535,715
4
3
null
2016-12-20 15:25:49.71 UTC
4
2021-03-10 14:59:11.657 UTC
2019-02-11 03:06:40.167 UTC
user10747134
null
null
1,501,960
null
1
39
angular|angular2-routing
9,321
<p>I figured out the problem/solution.</p> <p>We're seeing <code>Cannot read property '_lastPathIndex' of undefined</code> because at one point the Angular router expects a <code>_lastPathIndex</code> property on a <code>snapshot</code> object.</p> <p>The relevant part of the <a href="https://github.com/angular/angular/blob/master/modules/%40angular/router/src/create_url_tree.ts#L145">Angular source code</a> looks like this:</p> <pre><code>if (route.snapshot._lastPathIndex === -1) { return new Position(route.snapshot._urlSegment, true, 0); } </code></pre> <p>If <code>snapshot</code> is undefined, it will of course raise the error we're seeing.</p> <p>The problem can be solved by making <code>snapshot</code> not-undefined.</p> <p>Here's how I did it. My code is a little different from the OP's.</p> <p>I have a class called <code>MockActivatedRoute</code> that looks like this.</p> <pre><code>export class MockActivatedRoute { parent: any; params: any; constructor(options) { this.parent = options.parent; this.params = options.params; } } </code></pre> <p>Here's how I use it in my test.</p> <pre><code>let mockActivatedRoute = new MockActivatedRoute({ parent: new MockActivatedRoute({ params: Observable.of({ id: '1' }) }) }); </code></pre> <p>To make the error go away I just added a <code>snapshot</code> property to <code>MockActivatedRoute</code>.</p> <pre><code>export class MockActivatedRoute { parent: any; params: any; snapshot = {}; constructor(options) { this.parent = options.parent; this.params = options.params; } } </code></pre>
12,592,648
Date to Integer conversion in Java
<p>I have an int variable with following. How can I convert it to Date object and vice versa. </p> <pre><code>int inputDate=20121220; </code></pre>
12,592,654
1
0
null
2012-09-25 23:39:38.823 UTC
2
2017-11-16 19:40:58.24 UTC
2012-09-25 23:43:28.983 UTC
null
14,955
null
315,492
null
1
7
java|date
46,767
<p>Convert the value to a <code>String</code> and use <a href="http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer"><code>SimpleDateFormat</code></a> to parse it to a <code>Date</code> object:</p> <pre><code>int inputDate = 20121220; DateFormat df = new SimpleDateFormat("yyyyMMdd"); Date date = df.parse(String.valueOf(inputDate)); </code></pre> <p>The converse is similar, but instead of using <a href="http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#parse%28java.lang.String%29" rel="noreferrer"><code>parse</code></a>, use <a href="http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#format%28java.util.Date%29" rel="noreferrer"><code>format</code></a>, and convert from the resulting <code>String</code> to an <code>Integer</code>:</p> <pre><code>String s = date.format(date); int output = Integer.valueOf(s); </code></pre> <p>An alternative is to use <code>substring</code> and manually parse the <code>String</code> representation of your <code>Int</code>eger, though I <strong>strongly advise you against</strong> this:</p> <pre><code>Calendar cal = Calendar.getInstance(); String input = String.valueOf(inputDate); cal.set(Calendar.YEAR, Integer.valueOf(input.substring(0, 4))); cal.set(Calendar.MONTH, Integer.valueOf(input.substring(4, 6)) - 1); cal.set(Calendar.DAY_OF_MONTH, Integer.valueOf(input.substring(6))); Date date = cal.getTime(); </code></pre>
12,476,604
Processing of multipart/form-data request failed. Read timed out
<p>Other questions on Stack Overflow have addressed this question, but none of the answers provided have helped me to address the issue.</p> <p>I'm trying to upload a file of anywhere between 10 kB to 16 MB from an applet using Apache HTTP Commons. Everything works fine in my local environment.</p> <p>I'm receiving the following exception only on my production server (Tomcat 6.0, <a href="https://www.dailyrazor.com/" rel="noreferrer">https://www.dailyrazor.com/</a>), regardless of file size:</p> <pre><code>org.apache.commons.fileupload.FileUploadException: Processing of multipart/form-data request failed. Read timed out at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:384) at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:116) at com.actura.helper.UploadHelper.processUpload(UploadHelper.java:92) at com.actura.voice.upload.FileUploadServlet.process(FileUploadServlet.java:85) at com.actura.voice.upload.FileUploadServlet.doPost(FileUploadServlet.java:75) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) at org.apache.jk.server.JkCoyoteHandler.invoke(JkCoyoteHandler.java:190) at org.apache.jk.common.HandlerRequest.invoke(HandlerRequest.java:291) at org.apache.jk.common.ChannelSocket.invoke(ChannelSocket.java:769) at org.apache.jk.common.ChannelSocket.processConnection(ChannelSocket.java:698) at org.apache.jk.common.ChannelSocket$SocketConnection.runIt(ChannelSocket.java:891) at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:690) at java.lang.Thread.run(Thread.java:662) </code></pre> <p>This is the debugging log of Commons IO:</p> <pre><code>2012-Sep-18 11:26:28,446 [TP-Processor5] com.actura.voice.upload.MonitoredDiskFileItemFactory DEBUG inside MonitoredDiskFileItemFactory constructor (listener) 2012-Sep-18 11:26:28,794 [TP-Processor5] com.actura.voice.upload.MonitoredDiskFileItemFactory DEBUG inside MonitoredDiskFileItemFactory createItem 2012-Sep-18 11:26:28,800 [TP-Processor5] com.actura.voice.upload.MonitoredDiskFileItem DEBUG inside MonitoredDiskFileItem constructor 2012-Sep-18 11:26:28,800 [TP-Processor5] com.actura.voice.upload.MonitoredDiskFileItem DEBUG inside getOutputStream() 2012-Sep-18 11:26:28,802 [TP-Processor5] com.actura.voice.upload.MonitoredOutputStream DEBUG inside MonitoredOutputStream constructor 2012-Sep-18 11:26:28,803 [TP-Processor5] com.actura.voice.upload.MonitoredOutputStream DEBUG leaving MonitoredOutputStream contructor 2012-Sep-18 11:26:28,803 [TP-Processor5] com.actura.voice.upload.MonitoredDiskFileItem DEBUG leaving getOutputStream() 2012-Sep-18 11:26:28,803 [TP-Processor5] com.actura.voice.upload.MonitoredDiskFileItemFactory DEBUG inside MonitoredDiskFileItemFactory createItem 2012-Sep-18 11:26:28,803 [TP-Processor5] com.actura.voice.upload.MonitoredDiskFileItem DEBUG inside MonitoredDiskFileItem constructor 2012-Sep-18 11:26:28,803 [TP-Processor5] com.actura.voice.upload.MonitoredDiskFileItem DEBUG inside getOutputStream() 2012-Sep-18 11:26:28,803 [TP-Processor5] com.actura.voice.upload.MonitoredOutputStream DEBUG inside MonitoredOutputStream constructor 2012-Sep-18 11:26:28,803 [TP-Processor5] com.actura.voice.upload.MonitoredOutputStream DEBUG leaving MonitoredOutputStream contructor 2012-Sep-18 11:26:28,803 [TP-Processor5] com.actura.voice.upload.MonitoredDiskFileItem DEBUG leaving getOutputStream() 2012-Sep-18 11:26:28,803 [TP-Processor5] com.actura.voice.upload.MonitoredDiskFileItemFactory DEBUG inside MonitoredDiskFileItemFactory createItem 2012-Sep-18 11:26:28,803 [TP-Processor5] com.actura.voice.upload.MonitoredDiskFileItem DEBUG inside MonitoredDiskFileItem constructor 2012-Sep-18 11:26:28,803 [TP-Processor5] com.actura.voice.upload.MonitoredDiskFileItem DEBUG inside getOutputStream() 2012-Sep-18 11:26:28,803 [TP-Processor5] com.actura.voice.upload.MonitoredOutputStream DEBUG inside MonitoredOutputStream constructor 2012-Sep-18 11:26:28,803 [TP-Processor5] com.actura.voice.upload.MonitoredOutputStream DEBUG leaving MonitoredOutputStream contructor 2012-Sep-18 11:26:28,804 [TP-Processor5] com.actura.voice.upload.MonitoredDiskFileItem DEBUG leaving getOutputStream() 2012-Sep-18 11:26:28,804 [TP-Processor5] com.actura.voice.upload.MonitoredDiskFileItemFactory DEBUG inside MonitoredDiskFileItemFactory createItem 2012-Sep-18 11:26:28,804 [TP-Processor5] com.actura.voice.upload.MonitoredDiskFileItem DEBUG inside MonitoredDiskFileItem constructor 2012-Sep-18 11:26:28,804 [TP-Processor5] com.actura.voice.upload.MonitoredDiskFileItem DEBUG inside getOutputStream() 2012-Sep-18 11:26:28,804 [TP-Processor5] com.actura.voice.upload.MonitoredOutputStream DEBUG inside MonitoredOutputStream constructor 2012-Sep-18 11:26:28,804 [TP-Processor5] com.actura.voice.upload.MonitoredOutputStream DEBUG leaving MonitoredOutputStream contructor 2012-Sep-18 11:26:28,804 [TP-Processor5] com.actura.voice.upload.MonitoredDiskFileItem DEBUG leaving getOutputStream() processing folder... /home/dixieh83/public_html/ActuraVoiceRecorderDemo/temp 2012-Sep-18 11:27:47,062 [TP-Processor4] com.actura.voice.upload.MonitoredDiskFileItemFactory DEBUG inside MonitoredDiskFileItemFactory constructor (listener) 2012-Sep-18 11:27:47,461 [TP-Processor4] com.actura.voice.upload.MonitoredDiskFileItemFactory DEBUG inside MonitoredDiskFileItemFactory createItem 2012-Sep-18 11:27:47,461 [TP-Processor4] com.actura.voice.upload.MonitoredDiskFileItem DEBUG inside MonitoredDiskFileItem constructor 2012-Sep-18 11:27:47,462 [TP-Processor4] com.actura.voice.upload.MonitoredDiskFileItem DEBUG inside getOutputStream() 2012-Sep-18 11:27:47,462 [TP-Processor4] com.actura.voice.upload.MonitoredOutputStream DEBUG inside MonitoredOutputStream constructor 2012-Sep-18 11:27:47,462 [TP-Processor4] com.actura.voice.upload.MonitoredOutputStream DEBUG leaving MonitoredOutputStream contructor 2012-Sep-18 11:27:47,462 [TP-Processor4] com.actura.voice.upload.MonitoredDiskFileItem DEBUG leaving getOutputStream() 2012-Sep-18 11:27:47,462 [TP-Processor4] com.actura.voice.upload.MonitoredDiskFileItemFactory DEBUG inside MonitoredDiskFileItemFactory createItem 2012-Sep-18 11:27:47,462 [TP-Processor4] com.actura.voice.upload.MonitoredDiskFileItem DEBUG inside MonitoredDiskFileItem constructor 2012-Sep-18 11:27:47,462 [TP-Processor4] com.actura.voice.upload.MonitoredDiskFileItem DEBUG inside getOutputStream() 2012-Sep-18 11:27:47,462 [TP-Processor4] com.actura.voice.upload.MonitoredOutputStream DEBUG inside MonitoredOutputStream constructor 2012-Sep-18 11:27:47,462 [TP-Processor4] com.actura.voice.upload.MonitoredOutputStream DEBUG leaving MonitoredOutputStream contructor 2012-Sep-18 11:27:47,462 [TP-Processor4] com.actura.voice.upload.MonitoredDiskFileItem DEBUG leaving getOutputStream() 2012-Sep-18 11:27:47,463 [TP-Processor4] com.actura.voice.upload.MonitoredDiskFileItemFactory DEBUG inside MonitoredDiskFileItemFactory createItem 2012-Sep-18 11:27:47,463 [TP-Processor4] com.actura.voice.upload.MonitoredDiskFileItem DEBUG inside MonitoredDiskFileItem constructor 2012-Sep-18 11:27:47,463 [TP-Processor4] com.actura.voice.upload.MonitoredDiskFileItem DEBUG inside getOutputStream() 2012-Sep-18 11:27:47,463 [TP-Processor4] com.actura.voice.upload.MonitoredOutputStream DEBUG inside MonitoredOutputStream constructor 2012-Sep-18 11:27:47,463 [TP-Processor4] com.actura.voice.upload.MonitoredOutputStream DEBUG leaving MonitoredOutputStream contructor 2012-Sep-18 11:27:47,463 [TP-Processor4] com.actura.voice.upload.MonitoredDiskFileItem DEBUG leaving getOutputStream() 2012-Sep-18 11:27:47,463 [TP-Processor4] com.actura.voice.upload.MonitoredDiskFileItemFactory DEBUG inside MonitoredDiskFileItemFactory createItem 2012-Sep-18 11:27:47,463 [TP-Processor4] com.actura.voice.upload.MonitoredDiskFileItem DEBUG inside MonitoredDiskFileItem constructor 2012-Sep-18 11:27:47,463 [TP-Processor4] com.actura.voice.upload.MonitoredDiskFileItem DEBUG inside getOutputStream() 2012-Sep-18 11:27:47,463 [TP-Processor4] com.actura.voice.upload.MonitoredOutputStream DEBUG inside MonitoredOutputStream constructor 2012-Sep-18 11:27:47,463 [TP-Processor4] com.actura.voice.upload.MonitoredOutputStream DEBUG leaving MonitoredOutputStream contructor 2012-Sep-18 11:27:47,463 [TP-Processor4] com.actura.voice.upload.MonitoredDiskFileItem DEBUG leaving getOutputStream() </code></pre> <p>Other than this upload issue my applet works fine.</p> <p>This is the configuration of the server as described in my production server's <code>server.xml</code> file:</p> <pre><code>&lt;!-- Define an AJP 1.3 Connector on port 8009 --&gt; &lt;Connector address="127.0.0.1" port="9609" enableLookups="false" protocol="AJP/1.3" connectionTimeout="30000" maxThreads="50" minSpareThreads="1" maxSpareThreads="3" disableUploadTimeout="true" /&gt; </code></pre> <p>The speed of my internet connection is fine (2.01 Mbps down and 0.42 Mbps up), so this exception leaves me puzzled. I've already set <code>connectionTimeOut</code> to 3000000, but I still got the exception. Should I set <code>connectionTimeOut</code> to -1 to make it unlimited?</p> <p>File permissions are set to <code>777</code> on the directory from which I'm uploading and I'm using JDK version 7 to run the applet in the browser.</p> <p>Java console output:</p> <pre><code>Java Plug-in 10.7.2.10 Using JRE version 1.7.0_07-b10 Java HotSpot(TM) Client VM </code></pre> <p>When the upload fails, I get this in the console:</p> <pre><code>java.net.SocketException: Connection reset by peer: socket write error at java.net.SocketOutputStream.socketWrite0(Native Method) at java.net.SocketOutputStream.socketWrite(Unknown Source) at java.net.SocketOutputStream.write(Unknown Source) at org.apache.http.impl.io.AbstractSessionOutputBuffer.write(AbstractSessionOutputBuffer.java:169) at org.apache.http.impl.io.ContentLengthOutputStream.write(ContentLengthOutputStream.java:119) at org.apache.http.entity.mime.content.InputStreamBody.writeTo(InputStreamBody.java:70) at org.apache.http.entity.mime.HttpMultipart.doWriteTo(HttpMultipart.java:206) at org.apache.http.entity.mime.HttpMultipart.writeTo(HttpMultipart.java:224) at org.apache.http.entity.mime.MultipartEntity.writeTo(MultipartEntity.java:183) at org.apache.http.entity.HttpEntityWrapper.writeTo(HttpEntityWrapper.java:98) at org.apache.http.impl.client.EntityEnclosingRequestWrapper$EntityWrapper.writeTo(EntityEnclosingRequestWrapper.java:108) at org.apache.http.impl.entity.EntitySerializer.serialize(EntitySerializer.java:122) at org.apache.http.impl.AbstractHttpClientConnection.sendRequestEntity(AbstractHttpClientConnection.java:271) at org.apache.http.impl.conn.ManagedClientConnectionImpl.sendRequestEntity(ManagedClientConnectionImpl.java:197) at org.apache.http.protocol.HttpRequestExecutor.doSendRequest(HttpRequestExecutor.java:257) at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125) at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:712) at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:517) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:1066) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:1044) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:1035) at com.actura.app.util.ApplicationUtil.uploadUsingApache(ApplicationUtil.java:143) at com.actura.app.util.ApplicationUtil.saveWaveToServer(ApplicationUtil.java:90) at com.actura.app.capture.RecorderUI.saveButtonActionPerformed(RecorderUI.java:1856) at com.actura.app.capture.RecorderUI.access$17(RecorderUI.java:1824) at com.actura.app.capture.RecorderUI$7.actionPerformed(RecorderUI.java:1325) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.setPressed(Unknown Source) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent.processMouseEvent(Unknown Source) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$200(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) </code></pre> <p><strong>i have come to know that this might be a problem of my ISP. I just wonder if it is the problem of iSP why i can smoothly uses software like temviewer and Skype ??</strong></p> <p>The following is the code that performs the upload:</p> <pre><code>public static String uploadUsingApache(URL url, List&lt;File&gt; list, String userId, String accountId, String waveDuration) throws Exception { // The execution: DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost method = new HttpPost(url.toString()); MultipartEntity entity = new MultipartEntity(); entity.addPart("userId", new StringBody(userId, Charset .forName("UTF-8"))); entity.addPart(IVR_ACCOUNT_KEY, new StringBody(accountId, Charset .forName("UTF-8"))); entity.addPart(IVR_MP3LEN_KEY, new StringBody(waveDuration, Charset .forName("UTF-8"))); // FileBody fileBody = new FileBody(list.get(0)); // entity.addPart("file", fileBody); for (File f : list) { byte[] imageBytes = fileToByteArray(f); entity.addPart("attachment_field", new InputStreamKnownSizeBody( new ByteArrayInputStream(imageBytes), imageBytes.length, "audio/wav", f.getName())); method.setEntity(entity); } ResponseHandler&lt;String&gt; responseHandler = new BasicResponseHandler(); // HttpResponse response = httpclient.execute(method,responseHandler); String responseText = httpclient.execute(method, responseHandler); // error text if (responseText.contains("&lt;exception&gt;")) { responseText = responseText.replace("&lt;exception&gt;", ""); responseText = responseText.replace("&lt;/exception&gt;", ""); throw new Exception(responseText); } // System.out.println(" Status " +response.getStatusLine()); List&lt;String&gt; deleteList = Arrays.asList(responseText.split(",")); StringBuffer sb = new StringBuffer(); int cnt = 1; for (File f : list) { if (deleteList.contains(f.getName())) { sb.append(f.getName() + (cnt == deleteList.size() ? "" : ", ")); f.delete(); cnt++; } } if (deleteList.size() &gt; 1) { sb.append(" are "); } else if (deleteList.size() == 1) { sb.append(" is "); } else { } sb.append(" successfully saved."); return sb.toString(); } </code></pre> <p>When I press the upload button on my applet's GUI, it calls above method and at the same time the GUI freezes. 10 to 50 seconds later, the server throws the <code>FileUploadException</code>. The servlet notifies the applet about the exception, but the applet hangs for four or five minutes before notifying the user of the exception.</p> <p>Why is there so much delay if there's something wrong on the server side?</p>
18,543,887
2
3
null
2012-09-18 11:59:44.07 UTC
10
2016-07-28 13:50:54.263 UTC
2016-07-28 13:50:54.263 UTC
null
2,305,826
null
388,324
null
1
23
java|tomcat|upload|applet
86,722
<p>This helped me out a lot: <a href="http://blog.somepixels.net/en/502-proxy-error-uploading-from-apache-mod_proxy-to-tomcat-7/">http://blog.somepixels.net/en/502-proxy-error-uploading-from-apache-mod_proxy-to-tomcat-7/</a></p> <p>Basically in my server.xml I set it as:</p> <pre><code>&lt;Connector port="8080" protocol="HTTP/1.1" URIEncoding="UTF-8" connectionUploadTimeout="36000000" disableUploadTimeout="false" connectionTimeout="60000" redirectPort="8443" /&gt; </code></pre>
12,293,471
Passing arguments to an event handler
<p>In the below code, I am defining an event handler and would like to access the age and name variable from that without declaring the name and age globally. Is there a way I can say <code>e.age</code> and <code>e.name</code>?</p> <pre><code>void Test(string name, string age) { Process myProcess = new Process(); myProcess.Exited += new EventHandler(myProcess_Exited); } private void myProcess_Exited(object sender, System.EventArgs e) { // I want to access username and age here. //////////////// eventHandled = true; Console.WriteLine("Process exited"); } </code></pre>
12,293,499
2
2
null
2012-09-06 05:25:54.94 UTC
13
2013-09-13 17:20:29.573 UTC
2013-09-13 17:20:29.573 UTC
null
63,550
null
476,566
null
1
28
c#|events|event-handling|handler
53,561
<p>Yes, you could define the event handler as a lambda expression:</p> <pre><code>void Test(string name, string age) { Process myProcess = new Process(); myProcess.Exited += (sender, eventArgs) =&gt; { // name and age are accessible here!! eventHandled = true; Console.WriteLine("Process exited"); } } </code></pre>
12,436,073
DatePicker.OnDateChangedListener called twice
<p>I'm trying to create an app where the user selects a date from a DatePicker, and then a list is updated with some values. </p> <p>My GUI looks like this: </p> <pre><code> &lt;LinearLayout android:id="@+id/linearLayout1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" &gt; &lt;DatePicker android:id="@+id/datePicker" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:id="@+id/linearLayout2" android:layout_width="match_parent" android:layout_height="wrap_content" &gt; &lt;ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" &gt; &lt;/ListView&gt; &lt;/LinearLayout&gt; </code></pre> <p>Whereas my DatePicker initialization and handling look as follows:</p> <pre><code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); datePicker = (DatePicker) findViewById(R.id.datePicker); Calendar c = Calendar.getInstance(); year = c.get(Calendar.YEAR); month = c.get(Calendar.MONTH); day = c.get(Calendar.DAY_OF_MONTH); datePicker.init(year, month, day, dateSetListener); } private DatePicker.OnDateChangedListener dateSetListener = new DatePicker.OnDateChangedListener() { public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar c = Calendar.getInstance(); c.set(year, monthOfYear, dayOfMonth); System.out.println ("TEST"); } }; </code></pre> <p>In CatLog I see that "TEST" string is output twice, each time I play with the +/- buttons on the widget. What could be the problem?</p> <p>Note: I've "disabled" the list-updating code on purpose, in order to make sure that the problem is not related to the ListView, as in <a href="https://stackoverflow.com/questions/8553849/android-why-ondatechange-callback-is-called-twice" title="here">here</a></p>
20,499,834
9
2
null
2012-09-15 09:14:21.367 UTC
5
2020-09-17 09:56:29.577 UTC
2017-05-23 12:34:38.62 UTC
null
-1
null
697,567
null
1
48
android|events|datepicker
23,259
<p>When I test my application, method onDateSet called twice after accept the date selection and once when I canceled.</p> <p>I added a validation in the method onDateSet with parameter view, something like this</p> <pre><code>@Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth){ if (view.isShown()) { updateDate(year, monthOfYear, dayOfMonth); } } </code></pre> <p>I hope you serve</p>
12,492,979
How to get the output from console.timeEnd() in JS Console?
<p>I'd like to be able to get the string returned from <code>console.timeEnd('t')</code> in my Google Chrome Javascript Console.</p> <p>In this example below, I'd like one variable which would contain <code>"t: 0.276ms"</code></p> <pre><code>&gt; console.time('t'); console.timeEnd('t'); t: 0.276ms &lt; undefined </code></pre> <p>Is this something doable?</p>
12,504,825
4
2
null
2012-09-19 10:34:32.443 UTC
11
2018-11-26 01:29:57.857 UTC
null
null
null
null
422,957
null
1
58
javascript|google-chrome|google-chrome-devtools
46,813
<p>In Google Chrome 23.0.1262.2 (Official Build 155904) dev, it looks like it's impossible. The only way I found to be able to calculate time with accuracy is to use <code>window.performance.webkitNow()</code></p> <p>Here's a simple example:</p> <pre><code>var start = window.performance.now(); ... var end = window.performance.now(); var time = end - start; </code></pre> <p>Read more at <a href="http://updates.html5rocks.com/2012/08/When-milliseconds-are-not-enough-performance-now" rel="noreferrer">http://updates.html5rocks.com/2012/08/When-milliseconds-are-not-enough-performance-now</a></p>
12,276,507
Run script on mac prompt "Permission denied"
<p>I'm new to mac with not familiar on terminal command, i put the <code>dvtcolorconvert.rb</code> file on root directory of my volume, this ruby script can converting xcode 3 themes into xcode 4 themes format, which is <code>xxxxxxxx.dvtcolortheme</code> format. </p> <p>Then run the script <code>/dvtcolorconvert.rb ~/Themes/ObsidianCode.xccolortheme</code> on terminal, but it's always prompt "<em>Permission denied</em>".</p> <p>what's wrong with this? Anybody can help me solve this problem? Thanks.</p>
12,276,608
7
0
null
2012-09-05 07:27:20.39 UTC
26
2021-01-31 16:50:05.193 UTC
2012-09-05 07:52:24.813 UTC
null
667,820
null
1,479,822
null
1
105
macos|shell|terminal
394,204
<p>Please read the whole answer before attempting to run with <code>sudo</code></p> <p>Try running <code>sudo /dvtcolorconvert.rb ~/Themes/ObsidianCode.xccolortheme</code></p> <p>The sudo command executes the commands which follow it with 'superuser' or 'root' privileges. This should allow you to execute almost anything from the command line. That said, <strong>DON'T DO THIS!</strong> If you are running a script on your computer and don't need it to access core components of your operating system (I'm guessing you're not since you are invoking the script on something inside your home directory (~/)), then it should be running from your home directory, ie:</p> <p><code>~/dvtcolorconvert.rb ~/Themes/ObsidianCode.xccolortheme</code></p> <p>Move it to ~/ or a sub directory and execute from there. You should never have permission issues there and there wont be a risk of it accessing or modifying anything critical to your OS.</p> <p>If you are still having problems you can check the permissions on the file by running <code>ls -l</code> while in the same directory as the ruby script. You will get something like this:</p> <pre><code>$ ls -l total 13 drwxr-xr-x 4 or019268 Administ 12288 Apr 10 18:14 TestWizard drwxr-xr-x 4 or019268 Administ 4096 Aug 27 12:41 Wizard.Controls drwxr-xr-x 5 or019268 Administ 8192 Sep 5 00:03 Wizard.UI -rw-r--r-- 1 or019268 Administ 1375 Sep 5 00:03 readme.txt </code></pre> <p>You will notice that the readme.txt file says <code>-rw-r--r--</code> on the left. This shows the permissions for that file. The 9 characters from the right can be split into groups of 3 characters of 'rwx' (read, write, execute). If I want to add execute rights to this file I would execute <code>chmod 755 readme.txt</code> and that permissions portion would become <code>rwxr-xr-x</code>. I can now execute this file if I want to by running <code>./readme.txt</code> (./ tells the bash to look in the current directory for the intended command rather that search the $PATH variable).</p> <p><a href="https://stackoverflow.com/users/562283/schluchc">schluchc</a> alludes to looking at the man page for chmod, do this by running <code>man chmod</code>. This is the best way to get documentation on a given command, <code>man &lt;command&gt;</code></p>
18,786,546
Creating Drop Down Menu on click CSS
<p>I'm required to build a menu with 5 options, upon clicking a certain one a new sub menu is to appear. I have absolutely no idea how to do this.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>/**Navigation */ nav { border: 1px solid red; float: left; margin-right: 35px; min-height: 280px; } nav li { text-decoration: none; font-weight: normal; color: red; list-style: none; } /**Content */ #section { background-color: ; border: 1px solid; font: normal 12px Helvetica, Arial, sans-serif; margin-left: 180px; } .clearfix:before, .clearfix:after { content: " "; display: table; } .clearfix:after { clear: both; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="clearfix"&gt;&lt;/div&gt; &lt;nav&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="index.html" accesskey="1"&gt; Home &lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="Portfolio.html" accesskey="2"&gt; Portfolio &lt;/a&gt; &lt;/li&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="Commercial.html"&gt;Commercial&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="Residential.html"&gt;Residential&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="heritage.html"&gt;Heritage&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="Rennovations.html"&gt;Rennovations&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;li&gt;&lt;a href="services.html" accesskey="3"&gt; Services &lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="aboutus.html" accesskey="4"&gt; About Us &lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="contactus.html" accesskey="5"&gt; Contact Us &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt;</code></pre> </div> </div> </p>
18,787,019
8
5
null
2013-09-13 12:39:01.523 UTC
5
2017-02-28 06:40:59.29 UTC
2017-02-28 06:13:16.103 UTC
null
769,871
null
2,759,006
null
1
15
javascript|html|css
86,305
<p>CSS does not have a click handler. For this reason it is impossible to do with standard CSS. You could use something called the checkbox hack, but in my humble opinion, it's a bit clunky and would be awkward to work with inside a navigation menu like your use-case requires. For this reason I would suggest jQuery or Javascript... Here is a rather simple solution using jQuery.</p> <p>Basically, we hide the sub-nav from the start using <code>display: none;</code> Then, using jQuery, when ".parent" is clicked we toggle a class ".visible" to the sub-nav element (the nested UL) with <code>display: block;</code> which makes it appear. When clicked again, it disappears as the class is removed.</p> <p>Note that for this to work, every nested <code>&lt;UL&gt;</code> which is a "sub-nav" <strong>MUST</strong> have the <code>.sub-nav</code> class, and it's parent element (the <code>&lt;LI&gt;</code>) <strong>MUST</strong> have the <code>.parent</code> class. Also, since this uses jQuery, you will need to hook up a jQuery library to your site. You can do this by hosting it yourself and linking it like you normally would, or you can link it from <a href="https://developers.google.com/speed/libraries/devguide" rel="nofollow noreferrer">google's library service</a> (recommended). </p> <p><a href="http://jsfiddle.net/cRsZE/" rel="nofollow noreferrer"><strong>JSFiddle Demo</strong></a></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>$(document).ready(function() { $('.parent').click(function() { $('.sub-nav').toggleClass('visible'); }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#nav ul.sub-nav { display: none; } #nav ul.visible { display: block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;ul id="nav"&gt; &lt;li&gt;Home&lt;/li&gt; &lt;li class="parent"&gt;About &lt;ul class="sub-nav"&gt; &lt;li&gt;Johnny&lt;/li&gt; &lt;li&gt;Julie&lt;/li&gt; &lt;li&gt;Jamie&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;Contact&lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p>
3,470,693
Android get location or prompt to enable location service if disabled
<p>I've found bits and pieces of this answer scattered through other posts, but I wanted to record it here for others.</p> <p>How can I simply request the user's GPS and/or Network location and, if they haven't enabled the service, prompt them to do so?</p>
3,470,757
3
0
null
2010-08-12 18:13:44.497 UTC
11
2016-11-28 12:01:02.9 UTC
null
null
null
null
205,192
null
1
15
android|geolocation|gps
27,447
<p>If you want to capture the location on a button push, here's how you'd do it. If the user does not have a location service enabled, this will send them to the settings menu to enable it.</p> <p>First, you must add the permission "android.permission.ACCESS_COARSE_LOCATION" to your manifest. If you need GPS (network location isn't sensitive enough), add the permission "android.permission.ACCESS_FINE_LOCATION" instead, and change the "Criteria.ACCURACY_COARSE" to "Criteria.ACCURACY_FINE"</p> <pre><code>Button gpsButton = (Button)this.findViewById(R.id.buttonGPSLocation); gpsButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Start loction service LocationManager locationManager = (LocationManager)[OUTERCLASS].this.getSystemService(Context.LOCATION_SERVICE); Criteria locationCritera = new Criteria(); locationCritera.setAccuracy(Criteria.ACCURACY_COARSE); locationCritera.setAltitudeRequired(false); locationCritera.setBearingRequired(false); locationCritera.setCostAllowed(true); locationCritera.setPowerRequirement(Criteria.NO_REQUIREMENT); String providerName = locationManager.getBestProvider(locationCritera, true); if (providerName != null &amp;&amp; locationManager.isProviderEnabled(providerName)) { // Provider is enabled locationManager.requestLocationUpdates(providerName, 20000, 100, [OUTERCLASS].this.locationListener); } else { // Provider not enabled, prompt user to enable it Toast.makeText([OUTERCLASS].this, R.string.please_turn_on_gps, Toast.LENGTH_LONG).show(); Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); [OUTERCLASS].this.startActivity(myIntent); } } }); </code></pre> <p>My outer class has this listener set up</p> <pre><code>private final LocationListener locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { [OUTERCLASS].this.gpsLocationReceived(location); } @Override public void onProviderDisabled(String provider) {} @Override public void onProviderEnabled(String provider) {} @Override public void onStatusChanged(String provider, int status, Bundle extras) {} }; </code></pre> <p>Then, whenever you want to stop listening call this. You should at least make this call during your activity's onStop method.</p> <pre><code>LocationManager locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE); locationManager.removeUpdates(this.locationListener); </code></pre>
22,926,360
Malwarebytes gives trojan warning for basic C# "Hello World!" program
<p>Basically, I just ran a scan of my computer with <a href="https://en.wikipedia.org/wiki/Malwarebytes%27_Anti-Malware" rel="noreferrer">Malwarebytes</a> (updated the definitions before running), and it said my "helloworld" program written in C# has a <a href="http://en.wikipedia.org/wiki/Trojan_horse_%28computing%29" rel="noreferrer">trojan</a>.</p> <p>I know for a fact this is a false positive, as I only wrote the program 2-3 days ago and followed a small tutorial website to make the program that I trust. I am new to C#, but I can't see anything that would give a trojan warning at all.</p> <p><img src="https://i.stack.imgur.com/lVEtN.png" alt="Malwarebytes report"></p> <p>The program flags the executable, but not the source file.</p> <pre><code>using System; namespace HelloWorldApplication { class HelloWorld { static void Main(string[] args) { Console.WriteLine("\n\tHello World!"); Console.WriteLine("This is my first C# program.\nI'm so proud of myself!"); Console.WriteLine("\tTeehee!"); } } } </code></pre> <p>This is the code, written in <a href="http://en.wikipedia.org/wiki/Notepad++" rel="noreferrer">Notepad++</a>, and it is run from the command-line (<a href="http://en.wikipedia.org/wiki/Cygwin" rel="noreferrer">Cygwin</a>, actually). Why does it flags this? Is it something that, as a budding C# programmer, I should know about?</p>
22,926,407
3
9
null
2014-04-08 02:13:51.973 UTC
8
2017-06-24 01:18:20.407 UTC
2014-04-14 19:08:04.023 UTC
null
63,550
null
3,205,145
null
1
85
c#|false-positive|trojan
8,806
<p>The problem could be that the Backdoor.MSIL.PGen Trojan is typically called 'hello.exe'. The name of your executable is presumably 'hello.exe' or 'helloworld.exe'.</p> <p>Just rename your project or change the output executable to something not containing 'hello', and it should stop detecting it.</p> <p>This answer is somewhat speculative, but given the name of your project, and a history of over-aggressive detection of this malware (see <a href="https://forums.malwarebytes.org/index.php?showtopic=135095" rel="nofollow noreferrer">here</a>), it seems a reasonable stab.</p>
26,180,018
Uncaught TypeError: Cannot read property 'substr' of undefined
<p>Pardon me for not being clear, but have thia script that is really long. When I have it live, I get this error in Chrome's Console.</p> <blockquote> <p>Uncaught TypeError: Cannot read property 'substr' of undefined </p> </blockquote> <p>here is the snippet of code where it is reading from.</p> <pre><code>var formIddd = $('select[class~="FormField"]').get(numSelec).name.substr($('select[class~="FormField"]').get(numSelec).name.length-3,2); </code></pre> <p>I looked up substr on google and it appears to be a known property. I also found the classes. I have played with the lengths, but still getting stuck. It used to work until BigCommerce did an update. </p> <p>Any advice much appreciated, cheers.</p>
26,181,288
3
10
null
2014-10-03 13:37:06.313 UTC
null
2021-10-07 09:12:00.31 UTC
2014-10-03 13:41:20.02 UTC
null
1,267,304
null
3,034,386
null
1
2
javascript|jquery|bigcommerce
57,881
<p>You are not populating your array. The if check is false.</p> <p><img src="https://i.stack.imgur.com/5Ho1Z.png" alt="enter image description here"></p> <p>so basically you are doing this</p> <pre><code>var arrayOfSelectOfCountry = []; var numSelec = arrayOfSelectOfCountry[-1]; //undefined </code></pre> <p>which results in the error above. </p>
10,881,157
Read file names from directory in Bash
<p>I need to write a script that reads all the file names from a directory and then depending on the file name, for example if it contains R1 or R2, it will concatenates all the file names that contain, for example R1 in the name.</p> <p>Can anyone give me some tip how to do this?</p> <p>The only thing I was able to do is:</p> <pre><code>#!/bin/bash FILES="path to the files" for f in $FILES do cat $f done </code></pre> <p>and this only shows me that the variable FILE is a directory not the files it has.</p>
10,881,176
2
0
null
2012-06-04 12:18:59.75 UTC
1
2017-02-16 23:21:02.037 UTC
2017-02-16 23:21:02.037 UTC
null
6,862,601
null
476,595
null
1
5
bash
44,249
<p>To make the smallest change that fixes the problem:</p> <pre><code>dir="path to the files" for f in "$dir"/*; do cat "$f" done </code></pre> <p>To accomplish what you describe as your desired end goal:</p> <pre><code>shopt -s nullglob dir="path to the files" substrings=( R1 R2 ) for substring in "${substrings[@]}"; do cat /dev/null "$dir"/*"$substring"* &gt;"${substring}.out" done </code></pre> <p>Note that <code>cat</code> can take multiple files in one invocation -- in fact, if you aren't doing that, you usually don't need to use cat at all.</p>
11,252,199
Rails Deployment Environment on Windows
<p>Is there any good way at all to deploy a Ruby on Rails app built on Ruby 1.9.3 and Rails 3.2.6 with Apache on a Windows machine? I've spent hours scouring the forums, but all of the posts seem to be too old to work with the newest versions of Ruby and Rails. Mongrel is no longer under development and constantly causes Rails to crash, thin has only rudimentary Windows support and on my computer causes the Ruby runtime to "terminate itself in an unusual way", Passenger is Linux-only... I'm kinda lost at this point.</p> <p>Is there any stable, well-documented solution for serving Rails apps built on the newest frameworks with Apache on Windows?</p> <p><strong>UPDATE</strong></p> <p>I finally ended up working out my own solution. Check it out below for an up-to-date guide to Rails deployment on Windows.</p>
11,619,989
2
3
null
2012-06-28 20:16:31.78 UTC
11
2015-02-25 09:28:03.097 UTC
2012-07-23 20:29:35.813 UTC
null
1,489,331
null
1,489,331
null
1
11
ruby-on-rails|windows|ruby-on-rails-3|apache|deployment
4,967
<p><strong>UPDATE:</strong> I just returned to the company where I deployed with this process. After 11 months left completely unmaintained while the product was in use, the app and server environment are still functioning flawlessly :)</p> <p>Ok, it looks like I <em>finally</em> figured it out. Note that I am deploying to a small pool of users on a company intranet, so my solution may not work for everyone. I am using the excellent <a href="http://bitnami.org/stack/rubystack/">Bitnami RubyStack</a>, which contains an integrated Apache/Rails/MySQL installation. From there I did the following (worked for Rails 3.2.6 and Ruby 1.9.3):</p> <ol> <li><p>Shut down all Apache and Rails (WEBrick/Thin/Mongrel/Unicorn) servers. Exit out of your site if you have any development versions of it open. Clear your browser cache.</p></li> <li><p>If you haven't already, migrate your database to production mode. From the RubyStack command line, cd to your app's directory, then run <code>bundle exec rake db:migrate db:schema:load RAILS_ENV="production"</code>. WARNING: db:schema:load will delete all data in your production database.</p></li> <li><p>Precompile your assets: <code>bundle exec rake assets:precompile</code>. Note that this can take a <em>very</em> long time depending on your assets.</p></li> <li><p>In your <code>httpd.conf</code> (for me it's C:\RubyStack-3.2.5-0\apache2\conf\httpd.conf)</p> <p>Make sure necessary modules aren't commented out:</p> <pre><code>LoadModule expires_module modules/mod_expires.so LoadModule headers_module modules/mod_headers.so LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_balancer_module modules/mod_proxy_balancer.so LoadModule proxy_http_module modules/mod_proxy_http.so LoadModule rewrite_module modules/mod_rewrite.so </code></pre> <p>Then paste the following code somewhere in the file, with <code>app_name</code> being the folder name of your Rails app and <code>*:82</code> being any port number that Apache is listening to (signified by the command <code>Listen &lt;port_number&gt;</code>:</p> <pre><code>&lt;VirtualHost *:82&gt; # Your server's web or IP address goes here. # You can leave at localhost if deploying to # company intranet or some such thing. ServerName localhost # Customize the next two lines with your app's public directory DocumentRoot "C:/RubyStack-3.2.5-0/projects/app_name/public" &lt;Directory "C:/RubyStack-3.2.5-0/projects/app_name/public"&gt; Allow from all Options -MultiViews &lt;/Directory&gt; RewriteEngine On # Redirect all non-static requests to Rails server, # but serve static assets via Apache RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f RewriteRule ^/(.*)$ balancer://app_balancers%{REQUEST_URI} [P,QSA,L] # Serves dynamic rails assets from multiple servers # to improve performance. A Rails server such as # thin or WEBrick must be running on at least one of # these ports in order for Apache to serve your site &lt;Proxy balancer://app_balancers&gt; BalancerMember http://localhost:3001/ BalancerMember http://localhost:3002/ &lt;/Proxy&gt; # Support for far-futures expires header &lt;LocationMatch "^/assets/.*$"&gt; Header unset ETag FileETag None # RFC says only cache for 1 year ExpiresActive On ExpiresDefault "access plus 1 year" &lt;/LocationMatch&gt; &lt;/VirtualHost&gt; </code></pre></li> <li><p>Create one Windows Batch file (*.bat) for each of the Rails servers that your app will be using. Be sure to run them in production mode on the ports in your balancer. For instance, for your first server:</p> <pre><code>@echo off cd D:\your_app_folder rails s -e production -p 3001 </code></pre></li> <li><p>NOTE: The next few steps are necessary because the Rails servers need to run as services, or they will be shut down if there is no user logged in to the server. This also allows them to automatically restart upon failure. However, Windows cannot run Batch files as services, so we have to convert them to Windows EXEs. But standard Windows EXEs cannot be used as services because they don’t respond to the OnStart and OnStop methods. SO, to finally get our servers to run as Windows services, we have to use the Non-Sucking Service Manager as a frontend for our Windows EXEs.</p></li> <li><p>Download a BAT to EXE converter (just google for one) and make EXEs from your batch files. Make sure the converter you get has an option to hide the command windows when it runs (that option is usually called "Visibility" or something like that.)</p></li> <li><p>Download the <a href="http://nssm.cc">Non-Sucking Service Manager</a> (nssm.exe). Put it somewhere permanent and add that folder to your path.</p></li> <li><p>Start a command prompt. Type <code>nssm install &lt;servicename&gt;</code>, where <code>&lt;servicename&gt;</code> is whatever you want your service to be called. You will be prompted to enter the path to the application you wish to run as a service; choose the Windows EXEs you created in step 7, then click install, leaving commandline options blank.</p></li> <li><p>Repeat steps 6-8 for all of the ports in your balancer, creating a different service for every Rails server.</p></li> <li><p>Start all of the Services you just created (Start Menu –> Administrative Tools –> Services). The services should start immediately, but you must give the Rails servers at least 30 seconds to initialize.</p></li> <li><p>Start Apache. If it doesn't start, check to see if you included all the necessary modules (listed in first part of step 4).</p></li> <li><p>Navigate to <code>localhost:82</code>, substituting your port number for 82 if you customized it. You should see your site looking exactly the same as it did in development.</p></li> </ol> <p>Please let me know if this is too long to be appropriate for StackOverflow. I have just spent quite a lot of time struggling with this problem and figured it was high time someone wrote a up to date guide to Rails deployment on Windows (if there is one, I haven't seen it yet). Good luck, let me know if anyone has problems or enhancements for this!</p>
11,248,673
Hiding Google Translate bar
<p>I have the following code:</p> <pre><code>&lt;div style="" class="skiptranslate"&gt; &lt;iframe frameborder="0" style="visibility:visible" src="javascript:''" class="goog-te-banner-frame skiptranslate" id=":2.container"&gt;&lt;/iframe&gt; &lt;/div&gt; </code></pre> <p>I need to hide it but if I only hide the goog-te-banner-frame using:</p> <pre><code>.goog-te-banner-frame { display:none !important } </code></pre> <p>It still throws my header down. If I use this:</p> <pre><code>.skiptranslate { display:none !important } </code></pre> <p>It also hides the language selection dropdown because it shares the same class. I'd like to hide the skiptranslate div that CONTAINS the goog-te-banner-frame.</p> <p>How do I do that?</p> <p>Edit: This is actual code to "create" the translate div above:</p> <pre><code>&lt;div id="google_translate_element"&gt;&lt;/div&gt; &lt;script type="text/javascript"&gt; function googleTranslateElementInit() { new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE, autoDisplay: false, includedLanguages: ''}, 'google_translate_element');} &lt;/script&gt; &lt;script type="text/javascript" src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"&gt;&lt;/script&gt; </code></pre>
11,263,736
6
2
null
2012-06-28 16:10:02.79 UTC
3
2022-06-12 07:30:55.59 UTC
2012-06-28 22:20:56.813 UTC
null
338,403
null
338,403
null
1
15
css
39,095
<p>Ok, this works for some reason:</p> <pre><code>.goog-te-banner-frame.skiptranslate { display: none !important; } body { top: 0px !important; } </code></pre>
11,111,969
How to print member function address in C++
<p>It looks like <code>std::cout</code> can't print member function's address, for example:</p> <pre><code>#include &lt;iostream&gt; using std::cout; using std::endl; class TestClass { void MyFunc(void); public: void PrintMyFuncAddress(void); }; void TestClass::MyFunc(void) { return; } void TestClass::PrintMyFuncAddress(void) { printf("%p\n", &amp;TestClass::MyFunc); cout &lt;&lt; &amp;TestClass::MyFunc &lt;&lt; endl; } int main(void) { TestClass a; a.PrintMyFuncAddress(); return EXIT_SUCCESS; } </code></pre> <p>the result is something like this:</p> <pre><code>003111DB 1 </code></pre> <p>How can I print <code>MyFunc</code>'s address using <code>std::cout</code>?</p>
11,112,001
4
0
null
2012-06-20 02:14:51.26 UTC
9
2015-03-27 00:24:06.177 UTC
2012-06-20 04:44:12.423 UTC
null
722,720
null
722,720
null
1
17
c++|pointers|function-pointers|pointer-to-member
16,288
<p>I don't believe that there are any facilities provided by the language for doing this. There are overloads for <code>operator &lt;&lt;</code> for streams to print out normal <code>void*</code> pointers, but member function pointers are not convertible to <code>void*</code>s. This is all implementation-specific, but typically member function pointers are implemented as a pair of values - a flag indicating whether or not the member function is virtual, and some extra data. If the function is a non-virtual function, that extra information is typically the actual member function's address. If the function is a virtual function, that extra information probably contains data about how to index into the virtual function table to find the function to call given the receiver object.</p> <p>In general, I think this means that it's impossible to print out the addresses of member functions without invoking undefined behavior. You'd probably have to use some compiler-specific trick to achieve this effect.</p> <p>Hope this helps!</p>
11,260,833
Google N-Gram Web API
<p>I wish to use Google 2-grams for my project; but the data size renders searching expensive both in terms of speed and storage.<br> Is there a Web-API available for this purpose (in any language) ? The website <a href="http://books.google.com/ngrams/graph" rel="noreferrer">http://books.google.com/ngrams/graph</a> renders an image, can I get data values?</p>
11,290,260
2
1
null
2012-06-29 11:18:36.143 UTC
11
2014-07-10 20:50:45.183 UTC
null
null
null
null
1,400,306
null
1
22
asp.net-web-api
11,533
<p>Well, I got a round about way of doing that, using <a href="https://developers.google.com/bigquery/" rel="noreferrer">Google BigQuery</a><br> In that, trigrams are available in public domain. Using <a href="https://developers.google.com/bigquery/docs/hello_bigquery" rel="noreferrer">Command line access</a> did the job for me.</p>
11,422,220
Android - How to programmatically set the button style in a Linearlayout?
<p>I am programmatically creating a LinearLayout for an AlertDialog with some buttons.</p> <p>I <strong>WANT</strong> to do this:</p> <pre><code>&lt;LinearLayout android:id="@+id/footer" android:layout_width="fill_parent" style="@android:style/ButtonBar"&gt; </code></pre> <p>But with code like this:</p> <pre><code>LinearLayout buttons = new LinearLayout(parentContext); buttons.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams buttonsParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); topLayout.addView(buttons, buttonsParams); buttons.setLayoutParams(buttonsParams); Button btnAdd = new Button(context); btnAdd.setText("Add"); </code></pre> <p>How can I set the style of the buttons (use a button bar) programmitically?</p>
12,533,866
6
3
null
2012-07-10 21:24:45.783 UTC
9
2021-03-11 02:11:52.277 UTC
null
null
null
null
1,486,871
null
1
50
android|android-layout
84,973
<p>Hope I'm not too late to join the party :)</p> <p>Well, <em>Styles</em> can be applied to a <code>View</code> at initialization phase. For example:</p> <pre><code>LinearLayout button = new LinearLayout(context, null, android.R.style.ButtonBar); </code></pre>
10,947,982
How to remove gesture recogniser
<p>SO, I am adding a gesture recogniser to an overlay view. When tapped on screen i want this overlay to go away. Having said that adding a gesture recognizer overrides the "touch up inside" and other button click events. I need this back therefore i need to removegesturerecognizer. I can use this method however i have a problem. My code below - </p> <pre><code>- (void)helpClicked { CGRect visibleBounds = [self convertRect:[self bounds] toView:viewContainer]; CGFloat minimumVisibleX = CGRectGetMinX(visibleBounds); UIImageView * helpOverlay = [[UIImageView alloc]initWithFrame:CGRectMake(minimumVisibleX, 0, 1024, 768)]; UIImage * helpImage = [UIImage imageNamed:@"HelpOverLay.png"]; [helpOverlay setImage:helpImage]; helpOverlay.tag = 50; self.scrollEnabled = NO; [self addSubview:helpOverlay]; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissView)]; [self addGestureRecognizer:tap]; </code></pre> <p>}</p> <p>Here i am taking the overlay off the other view. </p> <pre><code>- (void) dismissView { UIView *overlay = [self viewWithTag:50]; [overlay removeFromSuperview]; self.scrollEnabled = YES; } </code></pre> <p>My question is how do i remove the gesture recognizer in the second method? I cant pass the variable tap into this method nor can i remove it in the previous method either. Any pointers? Ive been stuck with quite a lot of passing variable problems when it comes to events.</p>
31,730,523
11
1
null
2012-06-08 11:29:45.017 UTC
7
2022-07-27 07:17:00.24 UTC
null
null
null
null
955,237
null
1
51
iphone|objective-c|ios|ipad|ios4
71,993
<p>From the <a href="https://developer.apple.com/videos/wwdc/2015/?id=231" rel="noreferrer">WWDC 2015, Cocoa Touch Best Practices</a>, it is suggested that you keep a property or iVar if you need to access it later, and don't go with using <code>viewWithTag:</code>. </p> <h2>Moto: Properties instead of Tags</h2> <p>This saves you from some trouble:</p> <ol> <li>When dealing with multiple gestures, you remove the gesture that you want directly with accessing the property and remove it. (Without the need to iterate all the view's gestures to get the correct one to be removed)</li> <li>Finding the correct gesture by the tag when you are iterating, is very misleading when you have multiple tags on views, and when having conflicts with a specific tag</li> </ol> <blockquote> <p>(i.e) You implemented it first time with tags, and everything works as expected. Later you work on another functionality which lets say breaks this and causes undesired behavior that you don't expect it. Log doesn't give you a warning, and the best thing you can get depending on the case it's a crash signalizing <strong>unrecognized selector sent to instance</strong>. <em>Sometimes you won't get any of these</em>.</p> </blockquote> <h2>Solution</h2> <p>Declare the iVar</p> <pre><code>@implementation YourController { UITapGestureRecognizer *tap; } </code></pre> <p>Setup your view</p> <pre><code>- (void) helpClicked { //Your customization code //Adding tap gesture tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissView)]; [self addGestureRecognizer:tap]; } </code></pre> <p>Remove the gesture directly</p> <pre><code>- (void) dismissView { [self.view removeGestureRecognizer:tap]; } </code></pre>
13,220,923
Create custom google now cards
<p>Google provides a variety of 'cards' for Google Now (<a href="http://www.google.com/landing/now/" rel="noreferrer">http://www.google.com/landing/now/</a>). Is it possible to create your own cards? The system looks pretty modular, but I haven't found any documentation or instructions to do so. (I believe you need to supply the content of the card, and some way of signaling when it is supposed to be shown. There is probably just some interface that you have to implement.)</p> <p>If there is no documented solution, a hackish/undocumented way would be ok, too. I'm mostly curious how it works.</p> <p>Edit: Specifically, does somebody have knowledge about the internals of Google Now, e.g. by decompiling the .apk? What I've seen suggests it is pretty modular, and it should be fairly easy to drop another class into the .apk, or to maybe inject code using <a href="http://www.cydiasubstrate.com/" rel="noreferrer">Cydia Substrate</a>. I know that there is (as of Nov. 2013) no official way to add new cards.</p>
28,303,306
6
1
null
2012-11-04 17:18:37.573 UTC
23
2015-08-13 10:02:56.28 UTC
2013-11-28 19:56:12.773 UTC
null
143,091
null
143,091
null
1
58
android|google-now
29,879
<p>Actually Google announced last week that developers can now develop custom Google Now cards:</p> <p><a href="http://www.google.com/landing/now/integrations.html" rel="noreferrer">http://www.google.com/landing/now/integrations.html</a></p> <p>However, a developer guide seems not available yet.</p> <p><strong>Edit:</strong> On the end of the page they point out that: </p> <blockquote> <p>We'll let you know when we are able to onboard more partners</p> </blockquote>
30,562,642
Play Framework @routes.Assets.at Compilation Error
<p>I'm using Play 2.4.0 and I've been trying to follow the tutorial from the main page: <a href="https://playframework.com/" rel="noreferrer">https://playframework.com/</a> which is for Play 2.3 and after solving a couple of issues regarding changes in the Ebean ORM from version 2.3 to 2.4, I'm stuck with the following error:</p> <pre><code>Compilation error value at is not a member of controllers.ReverseAssets </code></pre> <p>My <code>index.scala.html</code>:</p> <pre><code>@(message: String) @main("Welcome to Play") { &lt;script type='text/javascript' src="@routes.Assets.at("javascripts/index.js")"&gt;&lt;/script&gt; &lt;form action="@routes.Application.addPerson()" method="post"&gt; &lt;input type="text" name="name" /&gt; &lt;button&gt;Add Person&lt;/button&gt; &lt;/form&gt; &lt;ul id="persons"&gt; &lt;/ul&gt; } </code></pre> <p>And my <code>routes</code> file:</p> <pre><code># Routes # This file defines all application routes (Higher priority routes first) # ~~~~ # Home page GET / controllers.Application.index() POST /person controllers.Application.addPerson() GET /persons controllers.Application.getPersons() # Map static resources from the /public folder to the /assets URL path GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset) </code></pre> <p>I have this same example working ok with Play 2.3.9</p> <p>And I can't see anything different about working with public assets in the docs for the 2.4.0: <a href="https://www.playframework.com/documentation/2.4.0/Assets" rel="noreferrer">https://www.playframework.com/documentation/2.4.0/Assets</a></p> <p>So... any help would be appreciated.</p>
30,569,848
1
7
null
2015-05-31 20:58:43.683 UTC
9
2015-06-01 09:21:55.1 UTC
2015-06-01 07:59:15.12 UTC
null
1,384,646
null
1,384,646
null
1
37
java|playframework|java-8|playframework-2.4
17,559
<p>Alright, to sum up the solution: Play lets you serve your assets in two different ways. The old fashioned and the new fingerprinted method introduced with sbt-web. In either case make sure you use right call in your view files:</p> <h2>Fingerprinted assets</h2> <p>This is the recommended way to serve assets in play. Fingerprinted assets make use of an aggressive caching strategy. You can read more about this topic here: <a href="https://playframework.com/documentation/2.4.x/Assets">https://playframework.com/documentation/2.4.x/Assets</a></p> <p><strong>routes config:</strong></p> <pre><code>GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset) </code></pre> <p>Make sure the type of <code>file</code> is indicated as <code>Asset</code></p> <p><strong>call in views:</strong></p> <pre><code>@routes.Assets.versioned("an_asset") </code></pre> <p><br></p> <h2>Old fashioned assets</h2> <p>This is basically the method used before the introduction of sbt-web.</p> <p><strong>routes config:</strong></p> <pre><code>GET /assets/*file controllers.Assets.at(path="/public", file) </code></pre> <p><strong>call in views:</strong></p> <pre><code>@routes.Assets.at("an_asset") </code></pre>
16,827,839
Access google plus client from multiple activities
<p>I'm developing an application in which i have integrated google plus. So far Its working fine, I am able to retrieve the user profile.</p> <p>But now i want to do the following:</p> <p>1)I have two activity <code>signInActivity</code> and <code>shareActivity</code>.</p> <p>2)If user is already signin using <code>signInActivity</code> then it should not ask for signin again in <code>shareActivity</code> and should directly share the content.</p> <p>3)If user is not signedin in the <code>signInActivity</code> and try to share data using <code>shareActivity</code>then app should signin the user and then only share the data. In this case if user goes back to the <code>signInActivity</code> then app should show that "you have already signedin"</p> <p>In short i want user signin to be <strong>Central</strong> within application so that if it is alrady signedin it should be accessible from any activity.</p> <p>I have heard about the access token but i dont know how to use it and document says that it expires in an hour which is not what i want.</p> <p>How can i make central google plus signin? is it possible? or i need to authenticate user in each activity?</p>
16,832,398
3
0
null
2013-05-30 04:16:57.063 UTC
8
2015-07-27 23:02:46.827 UTC
2013-05-30 04:22:59.133 UTC
null
1,509,703
null
1,629,527
null
1
24
android|google-plus|access-token
12,751
<p>Managing a separate instance of GoogleApiClient in each activity will <strong>not</strong> result in the user being asked to sign in multiple times.</p> <p>Google+ Sign-in (ie. GoogleApiClient) provides an interface to the Google accounts on the device and the Google Play services core service - it doesn't have state per GoogleApiClient instance. So once a device account has been authenticated for your app, new instances of GoogleApiClient will access the same state. GoogleApiClient is specifically designed to be a lightweight way to access the central state managed by Google Play services.</p> <p>You're in luck regarding access tokens! Google Play services takes care of all token management for you. So although access tokens only last for one hour, as you say, if you try to use your PlusClient to access a Google API and your access token has expired, Google Play services will transparently request a new access token for you and complete the call.</p> <p>Take a look at the first part of this Google I/O talk for more details:</p> <p><a href="http://www.youtube.com/watch?v=_KBHf1EODuk" rel="noreferrer">http://www.youtube.com/watch?v=_KBHf1EODuk</a></p>
16,628,748
Where in Wordpress DB are stored wp_cron tasks?
<p>I was looking in wp_options table but there is nothing like that eventhough I have set my cron tasks like:</p> <pre><code>add_action('init', function() { if ( !wp_next_scheduled('my_awesome_cron_hook') ) { wp_schedule_event(time(), 'hourly', 'my_awesome_cron_hook'); } }); </code></pre> <p>Or is it stored in some txt file in wordpress?</p>
16,628,818
1
0
null
2013-05-18 20:41:49.693 UTC
null
2016-10-22 17:54:08.4 UTC
null
null
null
null
1,285,810
null
1
37
wordpress|cron
25,186
<p>It's stored in the database inside <code>wp_options</code> under the <code>option_name</code> <code>cron</code>.</p> <p>You can get the array with: <code>_get_cron_array()</code> or <code>get_option('cron')</code>.</p> <p>See: <a href="http://core.trac.wordpress.org/browser/trunk/wp-includes/cron.php" rel="noreferrer">http://core.trac.wordpress.org/browser/trunk/wp-includes/cron.php</a></p>
16,641,057
How can I list the git subtrees on the root?
<p>For example, you can do a <code>git remote --verbose</code> and git will show all the remotes you have on your project, <code>git branch</code> will show all the branches and signal the current branch, but how to list all subtrees, without any destructive command? <code>git subtree</code> will give the usage examples, but won't list anything. subtree only have <code>add</code>,<code>pull</code>,<code>push</code>,<code>split</code>,<code>merge</code>.</p>
18,339,297
3
6
null
2013-05-20 00:43:00.66 UTC
17
2019-10-15 22:27:32.64 UTC
2015-06-02 18:51:33.263 UTC
null
230,468
null
647,380
null
1
49
git|git-subtree
26,763
<p>There isn't any explicit way to do that (at least, for now), the only available commands are listed here (as you noted yourself, but here's a reference for future seekers): <a href="https://github.com/git/git/blob/master/contrib/subtree/git-subtree.txt">https://github.com/git/git/blob/master/contrib/subtree/git-subtree.txt</a></p> <p>I went through the code (basically all this mechanism is a big shell script file), all of the tracking is done through commit messages, so all the functions use <code>git log</code> mechanism with lots of <code>grep</code>-ing to locate it's own data.</p> <p>Since subtree must have a folder with the same name in the root folder of the repository, you can run this to get the info you want (in Bash shell):</p> <pre><code>git log | grep git-subtree-dir | tr -d ' ' | cut -d ":" -f2 | sort | uniq </code></pre> <p>Now, this doesn't check whether the folder exist or not (you may delete it and the subtree mechanism won't know), so here's how you can list only the existing subtrees, this will work in any folder in the repository:</p> <pre><code> git log | grep git-subtree-dir | tr -d ' ' | cut -d ":" -f2 | sort | uniq | xargs -I {} bash -c 'if [ -d $(git rev-parse --show-toplevel)/{} ] ; then echo {}; fi' </code></pre> <p>If you're really up to it, propose it to Git guys to include in next versions:)</p>
16,582,901
Javascript/jQuery: Set Values (Selection) in a multiple Select
<p>I have a multiple select:</p> <pre><code>&lt;select name='strings' id="strings" multiple style="width:100px;"&gt; &lt;option value="Test"&gt;Test&lt;/option&gt; &lt;option value="Prof"&gt;Prof&lt;/option&gt; &lt;option value="Live"&gt;Live&lt;/option&gt; &lt;option value="Off"&gt;Off&lt;/option&gt; &lt;option value="On"&gt;On&lt;/option&gt; &lt;/select&gt; </code></pre> <p>I load data from my database. Then I have a string like this:</p> <pre><code>var values="Test,Prof,Off"; </code></pre> <p>How can I set this Values in the multiple select? Already tried change the string in an array and put it as value in the multiple, but doesnt work...! Can someone help me with this? THANKS!!!</p>
16,582,989
8
1
null
2013-05-16 08:48:40.557 UTC
15
2021-04-18 02:43:31.79 UTC
null
null
null
null
1,824,136
null
1
126
javascript|jquery|multiple-select
249,943
<p>Iterate through the loop using the value in a dynamic selector that utilizes the attribute selector.</p> <pre><code>var values="Test,Prof,Off"; $.each(values.split(","), function(i,e){ $("#strings option[value='" + e + "']").prop("selected", true); }); </code></pre> <p><strong>Working Example</strong> <a href="http://jsfiddle.net/McddQ/1/" rel="noreferrer">http://jsfiddle.net/McddQ/1/</a></p>
25,618,934
Lambda-Over-Lambda in C++14
<p>How following recursive lambda call ends/terminates ? </p> <pre><code>#include &lt;cstdio&gt; auto terminal = [](auto term) // &lt;---------+ { // | return [=] (auto func) // | ??? { // | return terminal(func(term)); // &gt;---------+ }; }; auto main() -&gt; int { auto hello =[](auto s){ fprintf(s,"Hello\n"); return s; }; auto world =[](auto s){ fprintf(s,"World\n"); return s; }; terminal(stdout) (hello) (world) ; return 0; } </code></pre> <p>What am I missing over here ?</p> <p><sup><a href="http://coliru.stacked-crooked.com/a/edecb386f07ada7d"><code>Running code</code></a></sup></p>
25,619,179
6
6
null
2014-09-02 08:23:36.623 UTC
23
2014-09-08 13:32:33.523 UTC
null
null
null
null
1,870,232
null
1
69
c++|lambda|c++14
4,314
<p>It's not a recursive function call, look at it step-by-step:</p> <ol> <li><code>terminal(stdout)</code> - this simply returns a lambda which has captured <code>stdout</code></li> <li>The result of 1. is called with the lambda <code>hello</code>, which executes the lambda (<code>func(term)</code>), the result of which is passed to <code>terminal()</code>, which simply returns a lambda as in 1.</li> <li>The result of 2. is called with the lambda <code>world</code>, which does the same as 2, this time the return value is discarded...</li> </ol>
25,717,740
Why is GCC tricked into allowing undefined behavior simply by putting it in a loop?
<p>The following is nonsensical yet compiles cleanly with <code>g++ -Wall -Wextra -Werror -Winit-self</code> (I tested GCC 4.7.2 and 4.9.0):</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; int main() { for (int ii = 0; ii &lt; 1; ++ii) { const std::string&amp; str = str; // !! std::cout &lt;&lt; str &lt;&lt; std::endl; } } </code></pre> <p>The line marked <code>!!</code> results in undefined behavior, yet is not diagnosed by GCC. However, commenting out the <code>for</code> line makes GCC complain:</p> <pre><code>error: ‘str’ is used uninitialized in this function [-Werror=uninitialized] </code></pre> <p>I would like to know: why is GCC so easily fooled here? When the code is not in a loop, GCC knows that it is wrong. But put the same code in a simple loop and GCC doesn't understand anymore. This bothers me because we rely quite a lot on the compiler to notify us when we make silly mistakes in C++, yet it fails for a seemingly trivial case.</p> <p>Bonus trivia:</p> <ul> <li>If you change <code>std::string</code> to <code>int</code> <strong>and</strong> turn on optimization, GCC will diagnose the error even with the loop.</li> <li>If you build the broken code with <code>-O3</code>, GCC literally calls the ostream insert function with a null pointer for the string argument. If you thought you were safe from null references if you didn't do any unsafe casting, think again.</li> </ul> <p>I have filed a GCC bug for this: <a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63203">https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63203</a> - I'd still like to get a better understanding here of what went wrong and how it may impact the reliability of similar diagnostics.</p>
25,720,743
2
12
null
2014-09-08 05:04:15.073 UTC
2
2014-09-10 11:19:15.533 UTC
2014-09-08 05:25:16.187 UTC
null
4,323
null
4,323
null
1
28
c++|gcc|g++|compiler-warnings|undefined-behavior
1,840
<blockquote> <p>I'd still like to get a better understanding here of what went wrong and how it may impact the reliability of similar diagnostics.</p> </blockquote> <p>Unlike Clang, GCC doesn't have logic to detect self-initialized references, so getting a warning here relies on the code for detecting use of uninitialized variables, which is quite temperamental and unreliable (see <a href="https://gcc.gnu.org/wiki/Better_Uninitialized_Warnings" rel="nofollow noreferrer">Better Uninitialized Warnings</a> for discussion).</p> <p>With an <code>int</code> the compiler can figure out that you write an uninitialized <code>int</code> to the stream, but with a <code>std::string</code> there are apparently too many layers of abstraction between an expression of type <code>std::string</code> and getting the <code>const char*</code> it contains, and GCC fails to detect the problem.</p> <p>e.g. GCC does give a warning for a simpler example with less code between the declaration and use of the variable, as long as you enable some optimization:</p> <pre><code>extern "C" int printf(const char*, ...); struct string { string() : data(99) { } int data; void print() const { printf("%d\n", data); } }; int main() { for (int ii = 0; ii &lt; 1; ++ii) { const string&amp; str = str; // !! str.print(); } } d.cc: In function ‘int main()’: d.cc:6:43: warning: ‘str’ is used uninitialized in this function [-Wuninitialized] void print() const { printf("%d\n", data); } ^ d.cc:13:19: note: ‘str’ was declared here const string&amp; str = str; // !! ^ </code></pre> <p>I suspect this kind of missing diagnostic is only likely to affect a handful of diagnostics which rely on heuristics to detect problems. These would be the ones that give a warning of the form "<em>may</em> be used uninitialized" or "<em>may</em> violate strict aliasing rules", and probably the "array subscript is above array bounds" warning. Those warnings are not 100% accurate and "complicated" logic like loops(!) can cause the compiler to give up trying to analyse the code and fail to give a diagnostic.</p> <p>IMHO the solution would be to add checking for self-initialized references at the point of initialization, and not rely on detecting it is uninitialized later when it gets used.</p>
63,196,042
npm does not support Node.js v12.18.3
<p>Can see it's been asked a dozen times but none of the solutions I've found have worked for me so far.</p> <p>I've installed the latest version of Node.js (12.18.3) on my Windows 10 PC and I'm trying to install a package using npm. When I input <code>npm -v</code> it comes back with 5.6.0, which to me looks out of date - but when I try and install a package or update npm, I get the following error every time:</p> <pre><code>npm WARN npm npm does not support Node.js v12.18.3 npm WARN npm You should probably upgrade to a newer version of node as we npm WARN npm can't make any promises that npm will work with this version. npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9. npm WARN npm You can find the latest version at https://nodejs.org/ npm ERR! cb.apply is not a function npm ERR! A complete log of this run can be found in: </code></pre> <p>I've tried uninstalling Node.js completely, deleting all node_modules folders and restarting my computer after a fresh install, but it's the same thing each time. I've also tried using <code>npm install -g npm</code> and <code>npm install npm@latest -g</code> but again, I get the same error.</p> <p>Any solutions here?</p>
63,337,788
12
6
null
2020-07-31 16:53:57.417 UTC
10
2022-07-03 15:52:38.823 UTC
null
null
null
null
5,431,507
null
1
70
node.js|npm
64,935
<p>I found the work-around !</p> <p>First you need to open your cmd line, and use &quot; <strong>npm install -g npm@latest</strong> &quot; you'll get the error like this</p> <pre><code>C:\Users\KimeruLenovo&gt;npm install -g npm@latest npm WARN npm npm does not support Node.js v14.7.0 npm WARN npm You should probably upgrade to a newer version of node as we npm WARN npm can't make any promises that npm will work with this version. npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9. npm WARN npm You can find the latest version at https://nodejs.org/ npm ERR! cb.apply is not a function npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\KimeruLenovo\AppData\Roaming\npm-cache\_logs\2020-08 10T09_36_56_388Z-debug.log </code></pre> <p>Go to the path where you can find the debug log( this file is found in your npm-cache folder) C:\Users\KimeruLenovo\AppData\Roaming</p> <p>Delete the NPM and NPM-Cache folder, but <strong>DO NOT</strong> reinstall node . once deleted go back to your comand line and re-use the command &quot; <strong>npm install -g npm@latest</strong> &quot;</p> <p>This should do the trick :)</p>
4,831,499
Setting live wallpaper programmatically
<p>Is it possible to set a live wallpaper using some lines of code. For example, i want to tell my users that a live wallpaper is available "click here to set it".</p>
4,832,022
2
4
null
2011-01-28 18:00:42.667 UTC
18
2017-04-15 19:06:38.59 UTC
2017-04-15 19:06:38.59 UTC
null
1,033,581
null
260,298
null
1
26
android|live-wallpaper
18,369
<p>Alright, just so I stop getting downvotes for an outdated answer. Please see Error 454's answer below for a more robust solution which will send the user directly to the wallpaper preview screen on Jelly Bean and up devices.</p> <p>========================================</p> <p>Here's how to start the wallpaper chooser, from which the user can select your wallpaper. The toast is just a way to explain to the user what's going on.</p> <pre><code>Toast toast = Toast.makeText(this, "Choose '&lt;WALLPAPER NAME&gt;' from the list to start the Live Wallpaper.",Toast.LENGTH_LONG); toast.show(); Intent intent = new Intent(); intent.setAction(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER); startActivity(intent); </code></pre>
4,315,840
The UAC prompt shows a temporary random Program Name for msi, can the correct name be displayed?
<p>I'm building an MSI installer for windows and sign the installer using signtool. When I run the .msi to test it, the UAC (User Account Control) prompt shows up to ask me if I want to allow the installation to proceed. That's fine, but the prompt shows a number of fields, and for the Program Name field it displays something like "403b3.msi". This is not the name of the msi I'm running.</p> <p>How can I get the correct Program Name to be displayed?</p>
4,315,846
2
0
null
2010-11-30 16:11:52.45 UTC
8
2015-04-17 07:56:33.98 UTC
2010-12-01 09:14:48.023 UTC
null
11,898
null
11,898
null
1
61
windows|certificate|uac|signtool
8,703
<p>Use the /d command line argument with the required program name when executing signtool to sign the msi.</p> <p>It appears that the windows installer creates a temporary copy of the msi file and assigns it a generated name before running it. If you don't use /d with signtool, you get to see the temporary filename which isn't very useful for your users.</p>
9,917,858
Understanding authentication in a Java Application Server
<p>I'm currently working on a project running on JBoss AS 7 that requires authentication from a variety of sources. I'm trying to get an understanding of the various components that combine to provide authentication.</p> <p>I have some assumptions / guesses as to how this all fits together, but I need to make sure that my understanding is correct. So below is what I understand to be the authentication process for JBoss AS7.</p> <hr> <p>You have a security realm that defines how users are authenticated. This realm is then exposed to your application in order to secure some or all of it. In AS7 this is configured in the &lt;subsystem xmlns="urn:jboss:domain:security:1.0"&gt; element.</p> <p>The realm can be configured to authenticate users against a variety of sources using login-modules, such as a database, LDAP, a local file or something else. Multiple login-modules can be defined, and you can specify some combination of login-modules must "succeed" in order for authentication to occur.</p> <p>The actual username and passwords are passed in via a mechanism defined in the web.xml file (for servlets), defined in the &lt;login-config&gt; element.</p> <hr> <p>Assuming that the above process is correct (and it may not be):</p> <ul> <li>Does this whole authentication process fall under a specification like JAAS, or is JAAS just a small or optional part of this procedure?</li> <li>Do all types of &lt;auth-methods&gt;'s (i.e. BASIC, DIGEST and FORM) work with all kinds of login-modules? <a href="https://docs.jboss.org/author/display/AS7/Securing+the+Management+Interfaces#SecuringtheManagementInterfaces-Authentication" rel="noreferrer">This page</a> would seem to suggest not, but I haven't seen any clear documentation matching &lt;login-module&gt; options &lt;login-config&gt; options.</li> <li>The username and password flow from a login-config to a login-module seems straight forward enough, but what happens with systems like OpenID or OAuth where there are intermediary steps (like redirection to external login pages)?</li> <li>How do projects like <a href="http://docs.jboss.org/seam/3/security/latest/reference/en-US/html_single/#security-authentication" rel="noreferrer">Seam 3 Security</a>, <a href="http://shiro.apache.org/" rel="noreferrer">Apache Shiro</a> and <a href="http://static.springsource.org/spring-security/site/" rel="noreferrer">Spring Security</a> fit into this picture?</li> </ul>
10,478,330
1
1
null
2012-03-29 01:09:05.09 UTC
8
2012-05-10 00:45:32.167 UTC
null
null
null
null
157,605
null
1
14
spring-security|jboss7.x|jaas|shiro|seam3
4,329
<p>JavaEE security specification leaves a lot of space to container implementors so I will focus on JBoss implementation to answer. </p> <p><strong>JBoss security implementation</strong></p> <p>JBoss relies on JAAS authentication to implement JavaEE security. That way it takes benefits from a stable API and can use <a href="http://docs.redhat.com/docs/en-US/JBoss_Enterprise_Application_Platform/5/html/Security_Guide/ch12.html">existing <code>LoginModule</code> implementations</a>. Login modules are used to authenticate a subject but also to add roles to <code>Subject</code>. JAAS provides mechanisms for authorization, permission checking and JBoss uses it internally.</p> <p>JAAS <a href="http://docs.oracle.com/javase/6/docs/api/javax/security/auth/spi/LoginModule.html?is-external=true">LoginModule</a> does not only supports password-based authentication but also token-based authentication.</p> <p><strong>Token based authentications</strong></p> <p>A good example of what can be done in JBoss thanks to JAAS is the <a href="https://community.jboss.org/wiki/JBossNegotiation">HTTP Negotiation support for Kerberos SPNEGO</a>: an additional <code>auth-method</code> named <code>SPNEGO</code> is implemented thanks to a Tomcat Authenticator and token validation uses <a href="http://docs.oracle.com/javase/6/docs/api/javax/security/auth/spi/LoginModule.html?is-external=true">JavaSE standard Kerberos LoginModule</a>.</p> <p>By the way, the LoginModule API is not a requirement, it may even be too complex for some protocols. For instance, the implementation to support <a href="https://community.jboss.org/wiki/OpenIDIntegrationWithPicketLink">OpenID with PicketLink</a> only uses Servlet API.</p> <p><strong>Third party security libraries</strong></p> <p>These libraries often provide security layers to an application running a JavaEE or pure Java context, even if it does not take benefits from JavaEE specifications for authentication or role-based authorization.</p> <p>Spring Security provides other abstractions than JavaEE security for applications developers to implement authentication and authorization, mainly thanks to <code>ServletFilter</code> when a web application is concerned. A large panel of choices is available to secure his application: it is possible to mix multiple options like: JAAS usage, JavaEE container security usage or Spring Security specific implementations (the case of OpenID and OAuth). There is no dependency to JavaEE either so it may be use almost in any situation when running on JavaSE. Most architect choose to build application security on Spring Security to have the liberty to switch specific implementations in the future.</p> <p>Apache Shiro is really similar to Spring Security but it is younger and probably easier to set up.</p> <p>Seam security does not rely on JavaEE security or JBoss but only on Servlet and JSF APIs. It is obviously the easiest option for JSF/Seam-based web application. Behind the scene, it uses <a href="http://www.jboss.org/picketlink">PicketLink</a> implementations.</p> <p><strong>As a conclusion</strong>, the question to use third party libraries in addition or in replacement to JavaEE security depends on architectural choices: application complexity, vendor independence and portability, control on implementations for bug fixes or improvements. In your specific context, having multiple authentication sources requires a flexible solution like Spring Security which supports <a href="http://static.springsource.org/spring-security/site/docs/2.0.x/reference/authentication-common-auth-services.html">authentication provider chaining</a> (or Shiro).</p>
10,004,565
Redis 10x more memory usage than data
<p>I am trying to store a wordlist in redis. The performance is great.</p> <p>My approach is of making a set called &quot;words&quot; and adding each new word via 'sadd'.</p> <p>When adding a file thats 15.9 MB and contains about a million words, the redis-server process consumes 160 MB of ram. How come I am using 10x the memory, is there any better way of approaching this problem?</p>
10,008,222
3
0
null
2012-04-04 03:33:37.003 UTC
26
2020-08-30 11:50:37.14 UTC
2020-08-30 11:50:37.14 UTC
null
5,740,428
null
815,382
null
1
25
performance|memory|redis
25,790
<p>Well this is expected of any efficient data storage: the words have to be indexed in memory in a dynamic data structure of cells linked by pointers. Size of the structure metadata, pointers and memory allocator internal fragmentation is the reason why the data take much more memory than a corresponding flat file.</p> <p>A Redis set is implemented as a hash table. This includes:</p> <ul> <li>an array of pointers growing geometrically (powers of two)</li> <li>a second array may be required when incremental rehashing is active</li> <li>single-linked list cells representing the entries in the hash table (3 pointers, 24 bytes per entry)</li> <li>Redis object wrappers (one per value) (16 bytes per entry)</li> <li>actual data themselves (each of them prefixed by 8 bytes for size and capacity)</li> </ul> <p>All the above sizes are given for the 64 bits implementation. Accounting for the memory allocator overhead, it results in Redis taking at least 64 bytes per set item (on top of the data) for a recent version of Redis using the jemalloc allocator (>= 2.4)</p> <p>Redis provides <a href="http://redis.io/topics/memory-optimization">memory optimizations</a> for some data types, but they do not cover sets of strings. If you really need to optimize memory consumption of sets, there are tricks you can use though. I would not do this for just 160 MB of RAM, but should you have larger data, here is what you can do.</p> <p>If you do not need the union, intersection, difference capabilities of sets, then you may store your words in hash objects. The benefit is hash objects can be optimized automatically by Redis using zipmap if they are small enough. The zipmap mechanism has been replaced by ziplist in Redis >= 2.6, but the idea is the same: using a serialized data structure which can fit in the CPU caches to get both performance and a compact memory footprint.</p> <p>To guarantee the hash objects are small enough, the data could be distributed according to some hashing mechanism. Assuming you need to store 1M items, adding a word could be implemented in the following way:</p> <ul> <li>hash it modulo 10000 (done on client side)</li> <li>HMSET words:[hashnum] [word] 1</li> </ul> <p>Instead of storing:</p> <pre><code>words =&gt; set{ hi, hello, greetings, howdy, bonjour, salut, ... } </code></pre> <p>you can store:</p> <pre><code>words:H1 =&gt; map{ hi:1, greetings:1, bonjour:1, ... } words:H2 =&gt; map{ hello:1, howdy:1, salut:1, ... } ... </code></pre> <p>To retrieve or check the existence of a word, it is the same (hash it and use HGET or HEXISTS).</p> <p>With this strategy, significant memory saving can be done provided the modulo of the hash is chosen according to the zipmap configuration (or ziplist for Redis >= 2.6):</p> <pre><code># Hashes are encoded in a special way (much more memory efficient) when they # have at max a given number of elements, and the biggest element does not # exceed a given threshold. You can configure this limits with the following # configuration directives. hash-max-zipmap-entries 512 hash-max-zipmap-value 64 </code></pre> <p>Beware: the name of these parameters have changed with Redis >= 2.6.</p> <p>Here, modulo 10000 for 1M items means 100 items per hash objects, which will guarantee that all of them are stored as zipmaps/ziplists.</p>
9,986,475
Expand tabs to spaces in vim only in python files?
<p>How do I have the tab key insert 4 spaces when I'm editing "*.py" files and not any other files?</p> <p>Following a recommendation from <a href="https://stackoverflow.com/questions/9864543/vim-and-pep-8-style-guide-for-python-code">Vim and PEP 8 -- Style Guide for Python Code</a>, I installed vim-flake8 (and vim-pathogen). This gives warnings when PEP8 style guidelines are violated. This is great, but I would for tabs to be expanded automatically in the first place when editing python files. I would like to have tab key actually insert tabs when editing other types of files.</p> <p>In other words, I want the following to apply when I'm editing python files and only python files:</p> <pre><code>set expandtab " tabs are converted to spaces set tabstop=4 " numbers of spaces of tab character set shiftwidth=4 " numbers of spaces to (auto)indent </code></pre>
9,986,497
1
0
null
2012-04-03 02:49:30.21 UTC
9
2012-04-03 03:06:08.093 UTC
2017-05-23 12:02:03.663 UTC
null
-1
null
249,226
null
1
38
python|coding-style|vim
11,242
<pre><code>autocmd Filetype python setlocal expandtab tabstop=4 shiftwidth=4 </code></pre> <p>Or even shorter:</p> <pre><code>au Filetype python setl et ts=4 sw=4 </code></pre>
9,761,507
Which pretty print library?
<p>So from a glance at hackage I can see 5 pretty printing libraries:</p> <ul> <li>good old HughesPJ in pretty</li> <li>wl-pprint-extras</li> <li>wl-pprint-terminfo</li> <li>wl-pprint</li> <li>ansi-wl-pprint</li> <li>wl-pprint-text</li> </ul> <p>Oh wait, was that 6? 6 pretty printing libraries... no wait, we'll come in again.</p> <p>Anyway, they're all Wadler-Leijen except of course HughesPJ. My understanding is that WL is simpler and faster, so is probably preferred for new code.</p> <p>wl-pprint and wl-pprint-extras seem to be the same... I can't tell what's "extra" about the latter, or what "Free" means here (the module is Text.PrettyPrint.Free).</p> <p>wl-pprint-terminfo and ansi-wl-pprint both seem to be variants with ANSI terminal colors and whatnot, and seem equivalent except that wl-pprint-terminfo doesn't have any docs.</p> <p>wl-pprint-text, of course, uses Text. I don't know how much difference that actually makes wrt speed.</p> <p>The thing that worries me about these is that many of them have many releases. This implies they've had features added, bugs fixed, etc. But have they all had the same bugs fixed? I'm inclined to favor ansi-wl-pprint because it has documentation and its last upload was in 2012, and has a bunch of releases which implies the author still works on it.</p> <p>But I don't know for sure. Anyone have any advice? And I'm sure others agree that 5 almost-but-not-quite copy-paste modules could do with some consolidation...</p>
9,761,548
1
1
null
2012-03-18 19:25:59.443 UTC
7
2012-03-18 19:43:41.013 UTC
null
null
null
null
742,186
null
1
40
haskell|pretty-print
4,498
<p>In no particular order:</p> <ul> <li><p>The "Free" in <code>Text.PrettyPrint.Free</code> means <a href="http://www.haskell.org/haskellwiki/Free_structure" rel="noreferrer">free monad</a>, as per the package description: "A free monad based on the Wadler/Leijen pretty printer"; its <code>Doc</code> type is parametrised on another type, and it has a <code>Monad</code> instance, allowing you to embed "effects" into <code>Doc</code> values. This is used by wl-pprint-terminfo to add formatting functionality; it's not not a competing package, but rather an extension library by the same author. See the list of additions in <a href="http://hackage.haskell.org/packages/archive/wl-pprint-extras/latest/doc/html/Text-PrettyPrint-Free.html" rel="noreferrer">wl-pprint-extras' documentation</a> compared to <a href="http://hackage.haskell.org/packages/archive/wl-pprint/latest/doc/html/Text-PrettyPrint-Leijen.html" rel="noreferrer">wl-pprint's list</a> for more detailed information on what it adds.</p></li> <li><p>wl-pprint-terminfo uses the <a href="http://hackage.haskell.org/package/terminfo" rel="noreferrer">terminfo</a> package to do formatting, so it'll only work on POSIX-y systems, whereas ansi-wl-pprint uses the <a href="http://hackage.haskell.org/package/ansi-terminal" rel="noreferrer">ansi-terminal</a> package, so it'll work on Windows.</p></li> <li><p>wl-pprint-text might be useful if you're working with <code>Text</code> already, but it's unlikely to have a major performance impact unless you're using the pretty printer <em>really</em> heavily; it's not exactly a massively computationally-intensive task.</p></li> </ul> <p>Unless I had specific requirements, I'd probably just use the pretty package, since it's one of the boot packages, and thus available everywhere. I'd go for ansi-wl-pprint if I wanted formatting, and wl-pprint-text if I was working with <code>Text</code>, but otherwise I don't really see a particularly compelling reason to use a third-party library.</p>
44,296,002
Confusion with commas in ternary expression
<p>I found the following interesting code today:</p> <pre><code>SomeFunction(some_bool_variable ? 12.f, 50.f : 50.f, 12.f) </code></pre> <p>I created a small sample to reproduce the behavior:</p> <pre><code>class Vector3f { public: Vector3f(float val) { std::cout &lt;&lt; "vector constructor: " &lt;&lt; val &lt;&lt; '\n'; } }; void SetSize(Vector3f v) { std::cout &lt;&lt; "SetSize single param\n"; } void SetSize(float w, float h, float d=0) { std::cout &lt;&lt; "SetSize multi param: " &lt;&lt; w &lt;&lt; ", " &lt;&lt; h &lt;&lt; ", " &lt;&lt; d &lt;&lt; '\n'; } int main() { SetSize(true ? 12.f, 50.f : 50.f, 12.f); SetSize(false ? 12.f, 50.f : 50.f, 12.f); } </code></pre> <p>(<a href="http://coliru.stacked-crooked.com/a/6c2286c8ea8f996f" rel="noreferrer">Live Sample</a>)</p> <p>The result I get from running the above code is:</p> <pre class="lang-none prettyprint-override"><code>clang++ -std=c++14 -O2 -Wall -pedantic -lboost_system -lboost_filesystem -pthread main.cpp &amp;&amp; ./a.out main.cpp:29:20: warning: expression result unused [-Wunused-value] SetSize(true ? 12.f, 50.f : 50.f, 12.f); ^~~~ main.cpp:30:21: warning: expression result unused [-Wunused-value] SetSize(false ? 12.f, 50.f : 50.f, 12.f); ^~~~ 2 warnings generated. SetSize multi param: 50, 12, 0 SetSize multi param: 50, 12, 0 </code></pre> <p>What I was expecting in <em>both</em> cases was that a single parameter would be passed to <code>SetSize(float)</code>. However, two parameters are passed which I find extremely confusing (especially since ternary has precedence over comma; so I assumed the comma was not delimiting function arguments in this case). For example, if using <code>true</code>, the ternary should result in <code>12.f, 50.f</code>. In this expression, the value to the left of the comma gets dropped/ignored, so I'd expect the end result to be:</p> <pre><code>SetSize(50.f); </code></pre> <p>The second part of the confusion is that whether we use <code>true</code> or <code>false</code> in the ternary, the same 2 values are passed to the function. The <code>true</code> case should be <code>h=12, w=50</code> I'd think...</p> <p>I see the compiler is trying to warn me about something, but I can't quite understand what's going on. Can someone decompose this logic and explain the result in a step by step fashion?</p>
44,296,079
3
7
null
2017-05-31 23:05:49.613 UTC
3
2017-08-16 23:59:16.7 UTC
2017-06-14 19:14:48.043 UTC
null
1,687,119
null
157,971
null
1
34
c++
1,874
<p>While the second part of the ternary operator is self contained, the third part is not. The grammar is as follows:</p> <blockquote> <p><em>conditional-expression</em>:</p> <blockquote> <p><em>logical-or-expression</em></p> <p><em>logical-or-expression ? expression : assignment-expression</em></p> </blockquote> </blockquote> <p>So your function call is effectively this:</p> <pre><code>SetSize((true ? (12.f, 50.f): 50.f), 12.f) </code></pre> <p>So the ternary expression <code>true ? (12.f, 50.f): 50.f</code> gets evaluated as the first parameter to the function. Then <code>12.f</code> is passed as the second value. The comma in this case is <em>not</em> the comma operator but the function parameter separator.</p> <p>From section 5.18 of the <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf" rel="noreferrer">C++ standard</a>:</p> <blockquote> <p><em>2</em> In contexts where comma is given a special meaning, [ <em>Example:</em> in lists of arguments to functions (5.2.2) and lists of initializers (8.5) — <em>end example</em> ] the comma operator as described in Clause 5 can appear only in parentheses. [ <em>Example:</em></p> <pre><code>f(a, (t=3, t+2), c); </code></pre> <p>has three arguments, the second of which has the value 5 . — <em>end example</em> ]</p> </blockquote> <p>If you want the last two subexpressions to be grouped together, you need to add parenthesis:</p> <pre><code>SetSize(true ? 12.f, 50.f : (50.f, 12.f)); SetSize(false ? 12.f, 50.f : (50.f, 12.f)); </code></pre> <p>Now you have a comma operator and the single argument version of <code>SetSize</code> gets called.</p>
43,969,489
Why is `(foo) = "bar"` legal in JavaScript?
<p>In Node.js's REPL (tested in SpiderMonkey as well) the sequence</p> <pre><code>var foo = null; (foo) = "bar"; </code></pre> <p>is valid, with <code>foo</code> subsequently equal to <code>"bar"</code> as opposed to <code>null</code>.</p> <p>This seems counterintuitive because one would think the parenthesis would at least dereference <code>bar</code> and throw <em>Invalid left-hand side in assignment`</em>.</p> <p>Understandably, when you do anything interesting it does fail in aforementioned way.</p> <pre><code>(foo, bar) = 4 (true ? bar : foo) = 4 </code></pre> <p>According to <a href="https://www.ecma-international.org/ecma-262/7.0/index.html#sec-left-hand-side-expressions" rel="noreferrer">ECMA-262 on LeftHandExpressions</a> (so far as I can interpret) are no valid non-terminals that would lead to a parenthetical being accepted.</p> <p>Is there something I'm not seeing?</p>
43,970,003
2
9
null
2017-05-14 22:42:30.72 UTC
8
2017-05-15 17:37:01.437 UTC
2017-05-15 12:15:43.227 UTC
null
63,550
null
877,165
null
1
47
javascript|ecma
2,746
<p>It's valid indeed. You're allowed to wrap any simple assignment target in parenthesis.</p> <p>The left hand part of the <code>=</code> operation is a <a href="https://www.ecma-international.org/ecma-262/7.0/index.html#prod-LeftHandSideExpression" rel="noreferrer"><code>LeftHandSideExpression</code></a> as you correctly identified. This can be tracked down through the various precendence levels (<a href="https://www.ecma-international.org/ecma-262/7.0/index.html#prod-NewExpression" rel="noreferrer"><code>NewExpression</code></a>, <a href="https://www.ecma-international.org/ecma-262/7.0/index.html#prod-MemberExpression" rel="noreferrer"><code>MemberExpression</code></a>) to a <a href="https://www.ecma-international.org/ecma-262/7.0/index.html#prod-PrimaryExpression" rel="noreferrer"><code>PrimaryExpression</code></a>, which in turn might be a <a href="https://www.ecma-international.org/ecma-262/7.0/index.html#prod-CoverParenthesizedExpressionAndArrowParameterList" rel="noreferrer"><code>Cover&shy;Parenthesized&shy;Expression&shy;And&shy;Arrow&shy;Parameter&shy;List</code></a>:</p> <pre><b>(</b> <i>Expression</i><sub>[In, ?Yield]</sub> <b>)</b></pre> <p>(actually, when parsed with target <code>PrimaryExpression</code>, it's a <a href="https://www.ecma-international.org/ecma-262/7.0/index.html#prod-ParenthesizedExpression" rel="noreferrer"><code>ParenthesizedExpression</code></a>).</p> <p>So it's valid by the grammar, at least. Whether it's actually valid JS syntax is determined by another factor: early error static semantics. Those are basically prose or algorithmic rules that make some production expansions invalid (syntax errors) in certain cases. This for example allowed the authors to reuse the array and object initialiser grammars for destructuring, but only applying certain rules. In the <a href="https://www.ecma-international.org/ecma-262/7.0/index.html#sec-assignment-operators-static-semantics-early-errors" rel="noreferrer">early errors for assignment expressions</a> we find</p> <blockquote> <p>It is an early <code>Reference Error</code> if <em>LeftHandSideExpression</em> is neither an <em>ObjectLiteral</em> nor an <em>ArrayLiteral</em> and <strong>IsValidSimpleAssignmentTarget</strong> of <em>LeftHandSideExpression</em> is <code>false</code>.</p> </blockquote> <p>We can also see this distinction in the <a href="https://www.ecma-international.org/ecma-262/7.0/index.html#sec-assignment-operators-runtime-semantics-evaluation" rel="noreferrer">evaluation of assignment expressions</a>, where simple assignment targets are evaluated to a reference that can be assigned to, instead of getting the destructuring pattern stuff like object and array literals.</p> <p>So what does that <a href="https://www.ecma-international.org/ecma-262/7.0/index.html#sec-static-semantics-static-semantics-isvalidsimpleassignmenttarget" rel="noreferrer">IsValidSimpleAssignmentTarget</a> do to <em>LeftHandSideExpressions</em>? Basically it allows assignments to property accesses and disallows assignments to call expressions. It doesn't state anything about plain <em>PrimaryExpressions</em> which have their <a href="https://www.ecma-international.org/ecma-262/7.0/index.html#sec-semantics-static-semantics-isvalidsimpleassignmenttarget" rel="noreferrer">own IsValidSimpleAssignmentTarget rule</a>. All it does is to extract the <em>Expression</em> between the parentheses through the <a href="https://www.ecma-international.org/ecma-262/7.0/index.html#sec-static-semantics-coveredparenthesizedexpression" rel="noreferrer">Covered&shy;Parenthesized&shy;Expression operation</a>, and then again check IsValidSimpleAssignmentTarget of that. In short: <code>(…) = …</code> is valid when <code>… = …</code> is valid. It'll yield <code>true</code> only for <a href="https://www.ecma-international.org/ecma-262/7.0/index.html#sec-identifiers-static-semantics-isvalidsimpleassignmenttarget" rel="noreferrer"><em>Identifiers</em></a> (like in your example) and properties.</p>
28,041,688
Force uninstall of Visual Studio
<p>While uninstalling Microsoft Visual Studio Ultimate 2015 Preview, it throws an error quoting "Microsoft Visual Studio Ultimate 2015 Preview has stopped working"</p> <p>Message Content Include: </p> <blockquote> <p>A problem caused the program to stop working correctly. Windows will close the program and notify you if a solution is available.</p> </blockquote> <p>I googled and found a utility that uninstalls visual studio 2010 <a href="http://blogs.msdn.com/b/heaths/archive/2014/08/20/visual-studio-2010-uninstall-utility-back-online.aspx" rel="noreferrer">here</a> but nothing exists for Visual Studio 2012, 2013 and 2015. My questions are:</p> <p>Is there any generic utility that uninstalls Visual Studio by Version ? </p> <p>Or Is there a way to forcefully uninstall visual studio 2012 onward without using the Program and Features menu?</p>
28,731,368
6
10
null
2015-01-20 09:24:55.53 UTC
30
2020-04-08 10:55:47.777 UTC
2020-04-08 10:55:47.777 UTC
null
2,231,314
null
2,231,314
null
1
104
visual-studio-2015|visual-studio-2013|visual-studio-2017|visual-studio-2019|uninstallation
324,036
<p>I was running in to the same issue, but have just managed a full uninstall by means of trusty old CMD:</p> <pre><code>D:\vs_ultimate.exe /uninstall /force </code></pre> <p>Where D: is the location of your installation media (mounted iso, etc).</p> <p>You could also pass /passive (no user input required - just progress displayed) or /quiet to the above command line.</p> <p>EDIT: Adding link below to MSDN article mentioning that this forcibly removes ALL installed components.</p> <p><a href="http://blogs.msdn.com/b/heaths/archive/2015/07/17/removing-visual-studio-components-left-behind-after-an-uninstall.aspx">http://blogs.msdn.com/b/heaths/archive/2015/07/17/removing-visual-studio-components-left-behind-after-an-uninstall.aspx</a></p> <p>Also, to ensure link rot doesn't invalidate this, adding brief text below from original article.</p> <p><em>Starting with Visual Studio 2013, you can forcibly remove almost all components. A few core components – like the .NET Framework and VC runtimes – are left behind because of their ubiquity, though you can remove those separately from Programs and Features if you really want.</em></p> <p><strong>Warning: This will remove all components regardless of whether other products require them. This may cause other products to function incorrectly or not function at all.</strong></p> <p>Good luck!</p>
7,887,481
How to get rid of 'java.lang.IllegalArgumentException: Unknown entity' while running a simple hibernate app?
<p>I am new to Hibernate. While creating a small app using it I got following exception:</p> <p>Exception in thread "main" java.lang.IllegalArgumentException: Unknown entity:<br> model.Students at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:223) at controller.Main.main(Main.java:50) </p> <p>Can anybody please help me out? </p> <p>The Entity classes are as follows:</p> <pre><code>Other details: NetBeans Version: 6.7.1 Hibernate : 3.2.5 </code></pre> <p>Entity Students</p> <pre><code>package model; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; @Entity public class Students implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; @OneToOne(cascade=CascadeType.ALL) private Address address; public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } } </code></pre> <p>Another Entity Class</p> <pre><code>package model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity public class Address implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String city; private String zip; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } } </code></pre> <p>The DAO file</p> <pre><code>package controller; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import model.Address; import model.Students; import org.hibernate.HibernateException; public class Main { public static void main(String arr[]) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("OneToOne2PU"); EntityManager em = emf.createEntityManager(); EntityTransaction tr= em.getTransaction(); try{ tr.begin(); Address add1 = new Address(); add1.setCity("pune"); add1.setZip("09"); Address add2 = new Address(); add2.setCity("mumbai"); add2.setZip("12"); Students s1 = new Students(); s1.setName("abc"); s1.setAddress(add1); Students s2 = new Students(); s2.setName("xyz"); s2.setAddress(add2); em.persist(s1); em.persist(s2); tr.commit(); emf.close(); } catch(HibernateException e){ e.printStackTrace(); } } } </code></pre> <p>The persistence.xml </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"&gt; &lt;persistence-unit name="OneToOnePU" transaction-type="JTA"&gt; &lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt; &lt;jta-data-source&gt;students&lt;/jta-data-source&gt; &lt;exclude-unlisted-classes&gt;false&lt;/exclude-unlisted-classes&gt; &lt;properties&gt; &lt;property name="hibernate.hbm2ddl.auto" value="create-tables"/&gt; &lt;property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect"/&gt; &lt;property name="hibernate.connection.username" value="app"/&gt; &lt;property name="hibernate.connection.password" value="app"/&gt; &lt;property name="hibernate.connection.url" value="jdbc:derby://localhost:1527/StudentsData"/&gt; &lt;/properties&gt; &lt;/persistence-unit&gt; &lt;/persistence&gt; </code></pre> <p>The hibernate.cfg.xml file</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"&gt; &lt;hibernate-configuration&gt; &lt;session-factory&gt; &lt;property name="hibernate.dialect"&gt;org.hibernate.dialect.DerbyDialect&lt;/property&gt; &lt;property name="hibernate.connection.driver_class"&gt;org.apache.derby.jdbc.ClientDriver&lt;/property&gt; &lt;property name="hibernate.connection.url"&gt;jdbc:derby://localhost:1527/sample&lt;/property&gt; &lt;property name="hibernate.connection.username"&gt;app&lt;/property&gt; &lt;property name="hibernate.connection.password"&gt;app&lt;/property&gt; &lt;mapping class="model.Students"/&gt; &lt;mapping class="model.Address"/&gt; &lt;/session-factory&gt; &lt;/hibernate-configuration&gt; </code></pre>
7,887,855
3
0
null
2011-10-25 09:50:13.39 UTC
2
2019-09-06 21:21:49.267 UTC
2011-10-25 09:57:14.483 UTC
null
280,244
null
227,046
null
1
10
hibernate|jakarta-ee|jpa
54,004
<p>Depends bit about project structure, but likely by adding following to persistence.xml directly under persistence-unit element.</p> <pre><code>&lt;class&gt;model.Students&lt;/class&gt; &lt;class&gt;model.Address&lt;/class&gt; </code></pre> <p>Exactly like this:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"&gt; &lt;persistence-unit name="OneToOnePU" transaction-type="JTA"&gt; &lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt; &lt;jta-data-source&gt;students&lt;/jta-data-source&gt; &lt;class&gt;model.Students&lt;/class&gt; &lt;class&gt;model.Address&lt;/class&gt; &lt;exclude-unlisted-classes&gt;false&lt;/exclude-unlisted-classes&gt; &lt;properties&gt; &lt;property name="hibernate.hbm2ddl.auto" value="create-tables"/&gt; &lt;property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect"/&gt; &lt;property name="hibernate.connection.username" value="app"/&gt; &lt;property name="hibernate.connection.password" value="app"/&gt; &lt;property name="hibernate.connection.url" value="jdbc:derby://localhost:1527/StudentsData"/&gt; &lt;/properties&gt; &lt;/persistence-unit&gt; &lt;/persistence&gt; </code></pre> <p>By the way, why do you configure properties like <em>hibernate.dialect</em> in both persistence.xml and hibernate.cfg.xml?</p>
11,779,252
Entity-Attribute-Value Table Design
<p>I am currently designing a database structure for the products section of an ecommerce platform. It needs to be designed in such a way that makes it possible to sell an infinite number of different types of products with an infinite number of different attributes. </p> <p>E.g. The attributes of a laptop would be RAM, Screen Size, Weight, etc. The attributes of a book would be Author, ISBN, Publisher, etc.</p> <p>It seems like an EAV structure would be most suitable.</p> <ul> <li>Select a product</li> <li>Product belongs to attribute set</li> <li>Attribute set contains attributes x and y <ul> <li>Attribute x is data type datetime (values stored in attribute_values_datetime)</li> <li>Attribute y is data type int (values stored in attribute_values_int)</li> </ul></li> <li>Each attribute definition denotes the type (i,e, x has column type -> datetype)</li> </ul> <p>Assuming the above, could I join the selection to the attribute_values_datetime table to get the right data without getting the result set and building a second query now that the table is known? Would there be a large performance hit constructing a query of this type or would the below be more suitable (although less functional)</p> <ul> <li>Select a product</li> <li>Product belongs to attribute set</li> <li>Attribute set contains attributes x and y <ul> <li>Attribute x is data type datetime but stored as TEXT in attribute_values</li> <li>Attribute y is data type int but stored as TEXT in attribute_values</li> </ul></li> </ul>
11,972,029
3
11
null
2012-08-02 14:11:45.193 UTC
11
2018-02-11 13:22:56.873 UTC
2012-08-02 14:19:41.91 UTC
null
769,237
null
1,014,570
null
1
27
mysql|sql|database-design|database-schema|entity-attribute-value
15,916
<p>I'm going to offer a contrary opinion to most of the comments on this question. While <em>EAV is EVIL</em> for all of the reasons that you can find thoroughly explained many times here on SO and DBA.SE and elsewhere, there is one really common application for which most of the things that are wrong with EAV are largely irrelevant and the (few) advantages of EAV are very much germane. That application is online product catalogs.</p> <p>The main problem with EAV is that it doesn't let the database do what it is really good at doing, which is helping to give proper context to different attributes of information about different entities by arranging them in a <em>schema</em>. Having a schema brings many, many advantages around accessing, interpreting and enforcing integrity of your data.</p> <p>The fact about product catalogs is that the attributes of a product are almost entirely irrelevant <em>to the catalog system</em> itself. Product catalog systems do (at most) three things with product attributes.</p> <ol> <li><p>Display the product attributes in a list to end users in the form: {attribute name}: {attribute value}.</p></li> <li><p>Display the attributes of multiple products in a comparison grid where attributes of different products line up against each other (products are usually columns, attributes are usually rows)</p></li> <li><p>Drive rules for something (e.g. pricing) based on particular attribute/value combinations.</p></li> </ol> <p>If all your system does is regurgitate information that is semantically irrelevant (to the system) then the schema for this information is basically unhelpful. In fact the schema <em>gets in the way</em> in an online product catalog, especially if your catalog has many diverse types of products, because you're always having to go back into the schema to tinker with it to allow for new product categories or attribute types.</p> <p>Because of how it's used, even the data type of an attribute value in a product catalog is not necessarily (vitally) important. For some attributes you may want to impose contraints, like "must be a number" or "must come from this list {...}". That depends on how important attribute consistency is to your catalog and how elaborate you want your implementation to be. Looking at the product catalogs of several online retailers I'd say most are prepared to trade off simplicity for consistency.</p> <p>Yes, EAV is evil, except when it isn't.</p>
11,547,296
add a new row in a table
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/171027/add-table-row-in-jquery">Add table row in jQuery</a> </p> </blockquote> <p>I want to add a new row to my table on a change event. Here is what I have so far:</p> <pre><code>$('#CourseID').change(function() { $('#CourseListTable &gt; tr &gt; td:last').append('&lt;td&gt;...&lt;/td&gt;'); }); </code></pre> <p>Here is my table:</p> <pre><code>&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl&lt;dynamic&gt;" %&gt; &lt;table id="CourseListTable"&gt; &lt;tr&gt; &lt;th&gt;Course ID&lt;/th&gt; &lt;th&gt;Course Section&lt;/th&gt; &lt;th&gt;Level&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;select name="CourseID" id="CourseID"&gt;&lt;/select&gt;&lt;/td&gt; &lt;td&gt;&lt;select name="CourseSection" id="CourseSection"&gt;&lt;/select&gt;&lt;/td&gt; &lt;td&gt;&lt;select name="Level" id="Level"&gt;&lt;/select&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>I am not able to get this to work. I am missing something over here can anyone let me know where my error lies? </p> <p>Thanks in advance.</p>
11,547,389
6
1
null
2012-07-18 17:45:57.617 UTC
1
2016-10-02 06:20:32.177 UTC
2017-05-23 10:30:56.513 UTC
null
-1
null
793,468
null
1
32
javascript|jquery|html-table
1,937
<p>You mention append Row but in your code you are appending just cells.</p> <p>If you need to actually append a full row, try this:</p> <pre><code>$('#CourseID').change(function() { $('&lt;tr/&gt;').append('&lt;td&gt;...&lt;/td&gt;').insertAfter('#CourseListTable tr:last'); }); </code></pre>
3,752,824
Delegate to an instance method cannot have null 'this'
<p>I am developing a C# .NET 2.0 application wherein at run-time one of two DLLs are loaded depending on the environment. Both DLLs contain the same functions, but they are not linked to the same address-offset. My question is regarding the function delegates in my application code.</p> <pre><code>public class MyClass { public delegate int MyFunctionDelegate(int _some, string _args); public MyFunctionDelegate MyFuncToCallFrmApp; public MyClass() : base() { this.MyFuncToCallFrmApp = new MyFunctionDelegate(this.MyFuncToCallFrmApp); // &lt;-- Exception thrown here. } public SomeFunction() { MyFuncToCallFrmApp(int _someOther, string _argsLocal); } } </code></pre> <p>When my code executes I get an <code>ArgumentException</code> of "Delegate to an instance method cannot have null 'this'." What am I doing wrong?</p>
3,752,965
5
3
null
2010-09-20 15:15:05.26 UTC
1
2011-09-28 00:02:27.927 UTC
2010-09-20 15:16:56.317 UTC
null
102,937
null
214,296
null
1
14
c#|delegates
43,383
<p>You need to assign a valid function (hosted by some class in the dynamically loaded dll) to your delegate variable. If the functions are static methods on classes with the <em>same name</em>, this is straightforward:</p> <pre><code>public MyClass() { this.MyFuncToCallFrmApp = ExternalClass.Function; } </code></pre> <p>If the functions are instance methods of classes with the same name, just create an instance and do the same thing (also note that as long as the delegate is in scope, it will prevent the <code>ExternalClass</code> instance from being garbage-collected - you may want to store the instance as a member variable to make that clearer):</p> <pre><code>public MyClass() { this.MyFuncToCallFrmApp = new ExternalClass().Function; } </code></pre> <p>If the dynamically-loaded classes have different names, you'll need to determine which one to call - in this example, I'm using a boolean member variable to decide whether or not to use a default assembly's class:</p> <pre><code>public MyClass() { if (this.defaultAssembly) { this.MyFuncToCallFrmApp = ExternalClass1.Function; } else { this.MyFuncToCallFrmApp = ExternalClass2.Function; } } </code></pre>
3,220,280
How do I install an old version of Django on virtualenv?
<p>I want to install some specific version of a package (in this case Django) inside the virtual environment. I can't figure it out.</p> <p>I'm on Windows XP, and I created the virtual environment successfully, and I'm able to run it, but how am I supposed to install the Django version I want into it? I mean, I know to use the newly-created <code>easy_install</code> script, but how do I make it install Django 1.0.7? If I do <code>easy_install django</code>, it will install the latest version. I tried putting the version number <code>1.0.7</code> into this command in various ways, but nothing worked.</p> <p>How do I do this?</p>
3,220,470
5
0
null
2010-07-10 17:55:47.21 UTC
18
2022-04-21 09:39:13.297 UTC
2022-04-21 09:39:13.297 UTC
null
5,446,749
null
76,701
null
1
100
python|django|setuptools|virtualenv
82,824
<p>There was never a Django 1.0.7. The 1.0 series only went up to 1.0.4. You can see all the releases in the <a href="http://code.djangoproject.com/browser/django/tags/releases" rel="noreferrer">tags section of the Django code repository</a>.</p> <p>However to answer your question, don't use <code>easy_install</code>, use <code>pip</code>. (If it's not already installed, do <code>easy_install pip</code>, then never touch easy_install again). Now you can do:</p> <pre><code>pip install Django==1.0.4 </code></pre>
3,758,023
How to use square cursor in a HTML input field?
<p>How can I use this square cursor (image below) in the text <code>&lt;input&gt;</code> tags?</p> <p><img src="https://i.stack.imgur.com/lbgjU.jpg" alt="C:\WIKIPEDIA" /></p>
3,758,063
6
0
null
2010-09-21 07:09:32.34 UTC
14
2021-12-23 04:02:40.363 UTC
2021-12-23 04:02:40.363 UTC
null
4,294,399
null
244,413
null
1
26
javascript|html|css|text-cursor
26,276
<h2>Sample</h2> <p><img src="https://i.stack.imgur.com/qWBoZ.png" alt="Sample"></p> <p>I've <a href="http://jsbin.com/ehuki3/3/edit" rel="noreferrer">changed how it works</a>, and it seems to solve a few issues :)</p> <ul> <li>Accepts any text a normal input can</li> <li>Backspace works</li> <li>Theoretically can support pasting text</li> </ul> <p>Usual caveats apply still, most notably the inability to visually see where the caret is.</p> <p>I'd think <strong>long and hard</strong> whether this solution is worth implementing, based on its drawbacks and usability issues.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() { var cursor; $('#cmd').click(function() { $('input').focus(); cursor = window.setInterval(function() { if ($('#cursor').css('visibility') === 'visible') { $('#cursor').css({ visibility: 'hidden' }); } else { $('#cursor').css({ visibility: 'visible' }); } }, 500); }); $('input').keyup(function() { $('#cmd span').text($(this).val()); }); $('input').blur(function() { clearInterval(cursor); $('#cursor').css({ visibility: 'visible' }); }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#cmd { font-family: courier; font-size: 14px; background: black; color: #21f838; padding: 5px; overflow: hidden; } #cmd span { float: left; padding-left: 3px; white-space: pre; } #cursor { float: left; width: 5px; height: 14px; background: #21f838; } input { width: 0; height: 0; opacity: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div id="cmd"&gt; &lt;span&gt;&lt;/span&gt; &lt;div id="cursor"&gt;&lt;/div&gt; &lt;/div&gt; &lt;input type="text" name="command" value="" /&gt;</code></pre> </div> </div> </p>
3,408,397
Asynchronously sending Emails in C#?
<p>I'm developing an application where a user clicks/presses enter on a certain button in a window, the application does some checks and determines whether to send out a couple of emails or not, then show another window with a message.</p> <p>My issue is, sending out the 2 emails slows the process noticeably, and for some (~8) seconds the first window looks frozen while it's doing the sending.</p> <p>Is there any way I can have these emails sent on the background and display the next window right away?</p> <p>Please don't limit your answer with "use X class" or "just use X method" as I am not all too familiarized with the language yet and some more information would be highly appreciated.</p> <p>Thanks.</p>
22,471,481
11
4
null
2010-08-04 18:05:56.71 UTC
21
2022-03-10 15:13:38.22 UTC
null
null
null
null
409,141
null
1
44
c#|visual-studio|email|asynchronous
61,238
<p>As of .NET 4.5 SmtpClient implements async awaitable method <a href="http://msdn.microsoft.com/en-us/library/hh193922%28v=vs.110%29.aspx"><code>SendMailAsync</code></a>. As a result, to send email asynchronously is as following:</p> <pre><code>public async Task SendEmail(string toEmailAddress, string emailSubject, string emailMessage) { var message = new MailMessage(); message.To.Add(toEmailAddress); message.Subject = emailSubject; message.Body = emailMessage; using (var smtpClient = new SmtpClient()) { await smtpClient.SendMailAsync(message); } } </code></pre>
3,988,485
Passing parameters to addTarget:action:forControlEvents
<p>I am using addTarget:action:forControlEvents like this:</p> <p><pre><code>[newsButton addTarget:self action:@selector(switchToNewsDetails) forControlEvents:UIControlEventTouchUpInside]; </pre></code></p> <p>and I would like to pass parameters to my selector "switchToNewsDetails". The only thing I succeed in doing is to pass the (id)sender by writing: <pre><code>action:@selector(switchToNewsDetails:)</pre></code></p> <p>But I am trying to pass variables like integer values. Writing it this way doesn't work :</p> <p><pre><code>int i = 0; [newsButton addTarget:self action:@selector(switchToNewsDetails:i) forControlEvents:UIControlEventTouchUpInside]; </pre></code></p> <p>Writing it this way does not work either:</p> <p><pre><code>int i = 0; [newsButton addTarget:self action:@selector(switchToNewsDetails:i:) forControlEvents:UIControlEventTouchUpInside]; </pre></code></p> <p>Any help would be appreciated :)</p>
3,988,570
13
9
null
2010-10-21 14:23:34.76 UTC
46
2022-05-11 20:57:36.583 UTC
2019-05-20 13:39:36.48 UTC
null
2,272,431
null
477,274
null
1
129
ios|objective-c|iphone|cocoa-touch|uicontrolevents
121,397
<pre><code>action:@selector(switchToNewsDetails:) </code></pre> <p>You do not pass parameters to <code>switchToNewsDetails:</code> method here. You just create a selector to make button able to call it when certain action occurs (touch up in your case). Controls can use 3 types of selectors to respond to actions, all of them have predefined meaning of their parameters:</p> <ol> <li><p>with no parameters</p> <pre><code>action:@selector(switchToNewsDetails) </code></pre></li> <li><p>with 1 parameter indicating the control that sends the message</p> <pre><code>action:@selector(switchToNewsDetails:) </code></pre></li> <li><p>With 2 parameters indicating the control that sends the message and the event that triggered the message: </p> <pre><code>action:@selector(switchToNewsDetails:event:) </code></pre></li> </ol> <p>It is not clear what exactly you try to do, but considering you want to assign a specific details index to each button you can do the following:</p> <ol> <li>set a tag property to each button equal to required index</li> <li><p>in <code>switchToNewsDetails:</code> method you can obtain that index and open appropriate deatails:</p> <pre><code>- (void)switchToNewsDetails:(UIButton*)sender{ [self openDetails:sender.tag]; // Or place opening logic right here } </code></pre></li> </ol>
3,875,312
Clever way to append 's' for plural form in .Net (syntactic sugar)
<p>I want to be able to type something like:</p> <pre><code>Console.WriteLine("You have {0:life/lives} left.", player.Lives); </code></pre> <p>instead of</p> <pre><code>Console.WriteLine("You have {0} {1} left.", player.Lives, player.Lives == 1 ? "life" : "lives"); </code></pre> <p>so that for <code>player.Lives == 1</code> the output would be: <code>You have 1 life left.</code><br> for <code>player.Lives != 1</code> : <code>You have 5 lives left.</code></p> <p>or</p> <pre><code>Console.WriteLine("{0:day[s]} till doomsday.", tillDoomsdayTimeSpan); </code></pre> <p>Some systems have that built-in. How close can I get to that notation in C#?</p> <p><strong>EDIT:</strong> Yes, I am specifically looking for syntactic sugar, and not a method to determine what singular/plural forms are.</p>
3,875,477
14
2
null
2010-10-06 17:34:17.653 UTC
19
2019-01-11 15:45:21.817 UTC
2010-10-06 17:45:33.057 UTC
null
93,422
null
93,422
null
1
58
c#|.net|string-formatting
23,181
<p>You can create a custom formatter that does that:</p> <pre><code>public class PluralFormatProvider : IFormatProvider, ICustomFormatter { public object GetFormat(Type formatType) { return this; } public string Format(string format, object arg, IFormatProvider formatProvider) { string[] forms = format.Split(';'); int value = (int)arg; int form = value == 1 ? 0 : 1; return value.ToString() + " " + forms[form]; } } </code></pre> <p>The <code>Console.WriteLine</code> method has no overload that takes a custom formatter, so you have to use <code>String.Format</code>:</p> <pre><code>Console.WriteLine(String.Format( new PluralFormatProvider(), "You have {0:life;lives} left, {1:apple;apples} and {2:eye;eyes}.", 1, 0, 2) ); </code></pre> <p>Output:</p> <pre><code>You have 1 life left, 0 apples and 2 eyes. </code></pre> <p>Note: This is the bare minimum to make a formatter work, so it doesn't handle any other formats or data types. Ideally it would detect the format and data type, and pass the formatting on to a default formatter if there is some other formatting or data types in the string.</p>
3,913,580
Get selected row item in DataGrid WPF
<p>I have a <code>DataGrid</code>, bound to Database table, I need to get the content of selected row in <code>DataGrid</code>, for example, I want to show in <code>MessageBox</code> content of selected row.</p> <p>Example of <code>DataGrid</code>:</p> <p><img src="https://i.stack.imgur.com/tsZH2.png" alt="enter image description here"></p> <p>So, if I select the second row, my <code>MessageBox</code> has to show something like: <em>646 Jim Biology</em>.</p>
3,913,791
14
0
null
2010-10-12 10:17:26.38 UTC
26
2021-08-23 13:51:05.06 UTC
2019-02-21 11:19:11.74 UTC
null
462,347
null
462,347
null
1
75
wpf|datagrid|selecteditem
252,725
<p>You can use the <code>SelectedItem</code> property to get the currently selected object, which you can then cast into the correct type. For instance, if your <code>DataGrid</code> is bound to a collection of <code>Customer</code> objects you could do this:</p> <pre class="lang-cs prettyprint-override"><code>Customer customer = (Customer)myDataGrid.SelectedItem; </code></pre> <p>Alternatively you can bind <code>SelectedItem</code> to your source class or <code>ViewModel</code>.</p> <pre class="lang-xml prettyprint-override"><code>&lt;Grid DataContext=&quot;MyViewModel&quot;&gt; &lt;DataGrid ItemsSource=&quot;{Binding Path=Customers}&quot; SelectedItem=&quot;{Binding Path=SelectedCustomer, Mode=TwoWay}&quot;/&gt; &lt;/Grid&gt; </code></pre>
3,408,706
Hexadecimal string to byte array in C
<p>Is there any standard C function that converts from <strong>hexadecimal string to byte array</strong>?<br> I do not want to write my own function.</p>
3,409,211
20
2
null
2010-08-04 18:40:10.36 UTC
27
2021-06-02 08:26:04.637 UTC
2016-02-09 15:04:06.18 UTC
null
147,407
null
33,885
null
1
66
c|string
169,216
<p>As far as I know, there's no standard function to do so, but it's simple to achieve in the following manner:</p> <pre><code>#include &lt;stdio.h&gt; int main(int argc, char **argv) { const char hexstring[] = "DEadbeef10203040b00b1e50", *pos = hexstring; unsigned char val[12]; /* WARNING: no sanitization or error-checking whatsoever */ for (size_t count = 0; count &lt; sizeof val/sizeof *val; count++) { sscanf(pos, "%2hhx", &amp;val[count]); pos += 2; } printf("0x"); for(size_t count = 0; count &lt; sizeof val/sizeof *val; count++) printf("%02x", val[count]); printf("\n"); return 0; } </code></pre> <hr> <h3>Edit</h3> <p>As Al pointed out, in case of an odd number of hex digits in the string, you have to make sure you prefix it with a starting 0. For example, the string <code>"f00f5"</code> will be evaluated as <code>{0xf0, 0x0f, 0x05}</code> erroneously by the above example, instead of the proper <code>{0x0f, 0x00, 0xf5}</code>.</p> <p>Amended the example a little bit to address the comment from @MassimoCallegari</p>
8,094,156
Know relationships between all the tables of database in SQL Server
<p>I wish to all know how the tables in my database are related to each other (i.e PK/FK/UK) and hence i created a database diagram of all my tables in SQL Server. The diagram that was created was not easily readable and had to scroll (horizontally and sometimes vertically) to see the table on the other end.</p> <p>In short SQL's db diagram are not UI friendly when it comes to knowing relationships between many tables. </p> <p>My (simple) Question: Is there something like database diagram which can do what db diagram did but in "good" way?</p>
8,095,137
9
2
null
2011-11-11 12:44:14.303 UTC
28
2022-05-24 17:50:33.91 UTC
2018-06-26 08:05:43.027 UTC
null
1,364,007
null
224,636
null
1
58
sql|sql-server|database|tsql
145,208
<p>Sometimes, a textual representation might also help; with this query on the system catalog views, you can get a list of all FK relationships and how the link two tables (and what columns they operate on).</p> <pre><code>SELECT fk.name 'FK Name', tp.name 'Parent table', cp.name, cp.column_id, tr.name 'Refrenced table', cr.name, cr.column_id FROM sys.foreign_keys fk INNER JOIN sys.tables tp ON fk.parent_object_id = tp.object_id INNER JOIN sys.tables tr ON fk.referenced_object_id = tr.object_id INNER JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id INNER JOIN sys.columns cp ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_id INNER JOIN sys.columns cr ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_id ORDER BY tp.name, cp.column_id </code></pre> <p>Dump this into Excel, and you can slice and dice - based on the parent table, the referenced table or anything else.</p> <p>I find visual guides helpful - but sometimes, textual documentation is just as good (or even better) - just my 2 cents.....</p>
8,215,303
How do I remove trailing whitespace from a QString?
<p>I want to remove all the trailing whitespace characters in a <code>QString</code>. I am looking to do what the Python function <code>str.rstrip()</code> with a <code>QString</code>.</p> <p>I did some Googling, and found this: <a href="http://www.qtforum.org/article/20798/how-to-strip-trailing-whitespace-from-qstring.html" rel="noreferrer">http://www.qtforum.org/article/20798/how-to-strip-trailing-whitespace-from-qstring.html</a></p> <p>So what I have right now is something like this:</p> <pre><code>while(str.endsWith( ' ' )) str.chop(1); while(str.endsWith( '\n' )) str.chop(1); </code></pre> <p>Is there a simpler way to do this? I want to keep all the whitespace at the beginning.</p>
8,216,059
10
2
null
2011-11-21 16:46:02.69 UTC
4
2021-04-22 08:54:55.11 UTC
2015-06-08 15:44:14.197 UTC
null
2,642,204
null
873,268
null
1
39
c++|string|qt|qt4|trim
62,647
<p><code>QString</code> has two methods related to trimming whitespace:</p> <ul> <li><a href="http://doc.qt.io/qt-5/qstring.html#trimmed" rel="noreferrer"><code>QString QString::trimmed() const</code></a><br> Returns a string that has whitespace removed from the start and the end.</li> <li><a href="http://doc.qt.io/qt-5/qstring.html#simplified" rel="noreferrer"><code>QString QString::simplified() const</code></a><br> Returns a string that has whitespace removed from the start and the end, and that has each sequence of internal whitespace replaced with a single space.</li> </ul> <p>If you want to remove only trailing whitespace, you need to implement that yourself. Here is such an implementation which mimics the implementation of <code>trimmed</code>:</p> <pre><code>QString rstrip(const QString&amp; str) { int n = str.size() - 1; for (; n &gt;= 0; --n) { if (!str.at(n).isSpace()) { return str.left(n + 1); } } return ""; } </code></pre>
4,265,123
Add HTTP Header to NSURLRequest
<p>Is there any way to add HTTP header to <code>NSURLRequest</code> object? I used to add them in <code>NSMutableURLRequest</code> using:</p> <pre><code>[request addValue:@"PC" forHTTPHeaderField:@"machineName"] </code></pre>
4,265,260
3
0
null
2010-11-24 09:18:07.977 UTC
16
2016-12-17 11:00:31.75 UTC
2016-12-17 11:00:31.75 UTC
null
3,618,581
null
488,434
null
1
51
iphone|objective-c|http|nsurlrequest
62,288
<p>I don't think you can modify the HTTP Headers of a <code>NSURLRequest</code>. I think you're trying to modify a <code>NSURLRequest</code> object that you didn't initialize?</p> <p>You could create a <code>mutableCopy</code> of your request and then set the header fields with the following method:</p> <pre><code> -(void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field. </code></pre> <p>After that you can <code>copy</code> the mutable request back onto your <code>NSURLRequest</code> variable.</p> <p><strong>EDIT</strong>: Added example below</p> <pre><code>/* Create request variable containing our immutable request * This could also be a paramter of your method */ NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.stackoverflow.com"]]; // Create a mutable copy of the immutable request and add more headers NSMutableURLRequest *mutableRequest = [request mutableCopy]; [mutableRequest addValue:@"Hless" forHTTPHeaderField:@"X-user-nick"]; // Now set our request variable with an (immutable) copy of the altered request request = [mutableRequest copy]; // Log the output to make sure our new headers are there NSLog(@"%@", request.allHTTPHeaderFields); </code></pre>
4,695,826
Efficient way to iterate through xml elements
<p>I have a xml like this:</p> <pre><code>&lt;a&gt; &lt;b&gt;hello&lt;/b&gt; &lt;b&gt;world&lt;/b&gt; &lt;/a&gt; &lt;x&gt; &lt;y&gt;&lt;/y&gt; &lt;/x&gt; &lt;a&gt; &lt;b&gt;first&lt;/b&gt; &lt;b&gt;second&lt;/b&gt; &lt;b&gt;third&lt;/b&gt; &lt;/a&gt; </code></pre> <p>I need to iterate through all <code>&lt;a&gt;</code> and <code>&lt;b&gt;</code> tags, but I don't know how many of them are in document. So I use <code>xpath</code> to handle that:</p> <pre><code>from lxml import etree doc = etree.fromstring(xml) atags = doc.xpath('//a') for a in atags: btags = a.xpath('b') for b in btags: print b </code></pre> <p>It works, but I have pretty big files, and <code>cProfile</code> shows me that <code>xpath</code> is very expensive to use.</p> <p>I wonder, maybe there is there more efficient way to iterate through indefinitely number of xml-elements?</p>
4,696,161
4
1
null
2011-01-14 20:52:57.25 UTC
16
2019-03-25 03:57:10.147 UTC
2019-03-25 03:57:10.147 UTC
null
1,033,581
null
277,262
null
1
22
python|lxml
48,164
<p>XPath should be fast. You can reduce the number of XPath calls to one:</p> <pre><code>doc = etree.fromstring(xml) btags = doc.xpath('//a/b') for b in btags: print b.text </code></pre> <p>If that is not fast enough, you could try <a href="http://www.ibm.com/developerworks/xml/library/x-hiperfparse/" rel="noreferrer">Liza Daly's fast_iter</a>. This has the advantage of not requiring that the entire XML be processed with <code>etree.fromstring</code> first, and parent nodes are thrown away after the children have been visited. Both of these things help reduce the memory requirements. Below is <a href="https://stackoverflow.com/a/7171543/190597">a modified version of <code>fast_iter</code></a> which is more aggressive about removing other elements that are no longer needed.</p> <pre><code>def fast_iter(context, func, *args, **kwargs): """ fast_iter is useful if you need to free memory while iterating through a very large XML file. http://lxml.de/parsing.html#modifying-the-tree Based on Liza Daly's fast_iter http://www.ibm.com/developerworks/xml/library/x-hiperfparse/ See also http://effbot.org/zone/element-iterparse.htm """ for event, elem in context: func(elem, *args, **kwargs) # It's safe to call clear() here because no descendants will be # accessed elem.clear() # Also eliminate now-empty references from the root node to elem for ancestor in elem.xpath('ancestor-or-self::*'): while ancestor.getprevious() is not None: del ancestor.getparent()[0] del context def process_element(elt): print(elt.text) context=etree.iterparse(io.BytesIO(xml), events=('end',), tag='b') fast_iter(context, process_element) </code></pre> <p><a href="http://www.ibm.com/developerworks/xml/library/x-hiperfparse/" rel="noreferrer">Liza Daly's article</a> on parsing large XML files may prove useful reading to you too. According to the article, lxml with <code>fast_iter</code> can be faster than <code>cElementTree</code>'s <code>iterparse</code>. (See Table 1).</p>
4,168,754
Competely removing an <iframe> border
<p>Does anybody know how to <b>completely</b> remove an iframe border? I am using Firefox 3.x and the iframe is set to <b>completely occupy</b> the browser window - <code>height="100%"</code> <code>width="100%"</code></p> <p>I have already set <code>frameBorder="0"</code> and <code>scrolling="no"</code> but there is some space remaining at the border between the window and the iframe. Is the problem with 100% width and height? Do I need to set more than 100%? By how much?</p>
4,168,770
5
1
null
2010-11-12 20:24:08.84 UTC
3
2018-03-28 03:02:46.037 UTC
null
null
null
null
140,970
null
1
11
html|css
60,770
<p>Do you mean the margin/padding?</p> <p>In the html file your iframe is displaying try the following CSS:</p> <pre><code>body { margin: 0; padding 0; } </code></pre> <p><em>edit:</em> It could also be similar for your iframe element itself. If the above doesn't work, in the parent html page try:</p> <pre><code>iframe { padding: 0; margin: 0; } </code></pre>
4,809,314
ImageMagick is converting only the first page of the pdf
<p>I am having some trouble with ImageMagick.</p> <p>I have installed GhostScript v9.00 and ImageMagick-6.6.7-1-Q16 on Windows 7 - 32Bit</p> <p>When I run the following command in cmd</p> <p><strong>convert D:\test\sample.pdf D:\test\pages\page.jpg</strong></p> <p>only the first page of the pdf is converted to pdf. I have also tried the following command</p> <p><strong>convert D:\test\sample.pdf D:\test\pages\page-%d.jpg</strong></p> <p>This creates the first jpg as page-0.jpg but the other are not created. I would really appreciated if someone can shed some light on this. Thanks.</p> <p><strong>UPDATE:</strong></p> <p>I have ran the command using -debug "All"</p> <p>one of the many lines out put says:</p> <pre><code>2011-01-26T22:41:49+01:00 0:00.727 0.109u 6.6.7 Configure Magick[5800]: nt-base.c/NTGhostscriptGetString/1008/Configure registry: "HKEY_CURRENT_USER\SOFTWARE\GPL Ghostscript\9.00\GS_DLL" (failed) </code></pre> <p>Could it maybe have something to do with GhostScript after all?</p>
4,809,353
5
3
null
2011-01-26 19:53:58.43 UTC
10
2021-04-09 01:26:34.653 UTC
2013-06-05 16:20:53.783 UTC
null
385,913
null
295,654
null
1
27
pdf|imagemagick
20,856
<p>You can specify which page to convert by putting a number in [] after the filename:</p> <pre><code>convert D:\test\sample.pdf[7] D:\test\pages\page-7.jpg </code></pre> <p>It should have, however, converted all pages to individual images with your command.</p>
4,065,085
Safe dereferencing in Python
<p>Groovy has a nice operator for safe dereferencing, which helps to avoid NullPointerExceptions:</p> <pre><code>variable?.method() </code></pre> <p>The <code>method</code> will only be called, if <code>variable</code> is not <code>null</code>.</p> <p>Is there a way to do the same in Python? Or do I have to write <code>if variable: variable.method()</code>?</p>
4,065,309
5
12
null
2010-10-31 21:00:34.79 UTC
6
2021-06-21 01:17:28.143 UTC
2010-11-01 09:59:56.593 UTC
null
6,509
null
238,134
null
1
40
python|groovy|null|nullpointerexception
18,063
<p><strong>EDIT 2021:</strong></p> <p>There is a new package that is sort of a hack featuring exactly this functionality in Python. Here is the repo: <a href="https://github.com/paaksing/nullsafe-python" rel="noreferrer">https://github.com/paaksing/nullsafe-python</a></p> <pre class="lang-py prettyprint-override"><code>from nullsafe import undefined, _ value = _(variable).method() assert value is undefined assert not value assert value == None </code></pre> <p>Works with <code>AttributeError</code> and <code>KeyError</code> aswell</p> <pre class="lang-py prettyprint-override"><code>dic = {} assert _(dic)[&quot;nah&quot;] is undefined assert _(dic).nah is undefined </code></pre> <p>The wrapped object typings will remain effective.</p> <hr /> <ol> <li><p>No, there isn't.</p> </li> <li><p>But to check for <code>None</code>, you don't write <code>if x:</code>, you write <code>if x is None:</code>. This is an important distinction - <code>x</code> evaluates to <code>False</code> for quite a few values that are propably perfectly valid (most notably 0-equivalent numbers and empty collections), whereas <code>x is None</code> <strong>only</strong> evaluates to <code>True</code> if the reference <code>x</code> points to the singleton object <code>None</code>.</p> </li> <li><p>From personal experience, such an operator would be needed very rarely. Yes, <code>None</code> is sometimes used to indicate no value. But somehow - maybe because idiomatic code returns <a href="http://en.wikipedia.org/wiki/Null_object" rel="noreferrer">null objects</a> where sensible or throws exceptions to indicate critical failure - I only get an <code>AttributeError: 'NoneType' object has no attribute '...'</code> twice a month.</p> </li> <li><p>I would argue that this might be a misfeature. <code>null</code> has two meanings - &quot;forgot to initialize&quot; and &quot;no data&quot;. The first <strong>is an error and should throw an exception</strong>. The second case usually requires more elaborate handling than &quot;let's just not call this method&quot;. When I ask the database/ORM for a <code>UserProfile</code>, it's not there and I get <code>null</code> instead... do I want to silently skip the rest of the method? Or do I really want to (when in &quot;library code&quot;) throw an approriate exception (so &quot;the user (code)&quot; knows the user isn't there and can react... or ignore it) or (when I'm coding a specific feature) show a sensible message (&quot;That user doesn't exist, you can't add it to your friend list&quot;) to the user?</p> </li> </ol>
4,279,478
Largest circle inside a non-convex polygon
<p>How can I find the largest circle that can fit inside a concave polygon? </p> <p>A brute force algorithm is OK as long as it can handle polygons with ~50 vertices in real-time.</p>
4,279,633
7
5
null
2010-11-25 17:15:28.713 UTC
32
2021-06-29 16:21:52.34 UTC
2017-10-22 02:02:12.73 UTC
null
8,756,717
null
233,904
null
1
53
algorithm|polygon|computational-geometry|geometry
29,771
<p>The key to solving this problem is first making an observation: the center of the largest circle that will fit inside an arbitrary polygon is the point that is:</p> <ol> <li>Inside the polygon; and</li> <li>Furthest from any point on the edges of the polygon.</li> </ol> <p>Why? Because every point on the edge of a circle is equidistant from that center. By definition, the largest circle will have the largest radius and will touch the polygon on at least two points so if you find the point inside furthest from the polygon you've found the center of the circle.</p> <p>This problem appears in geography and is solved iteratively to any arbitrary precision. Its called the Poles of Inaccessibility problem. See <a href="http://web.archive.org/web/20140629230429/http://cuba.ija.csic.es/~danielgc/papers/Garcia-Castellanos,%20Lombardo,%202007,%20SGJ.pdf" rel="noreferrer">Poles of Inaccessibility: A Calculation Algorithm for the Remotest Places on Earth</a>.</p> <p>The basic algorithm works like this:</p> <ol> <li>Define R as a rectilinear region from (x<sub>min</sub>,y<sub>min</sub>) to (x<sub>max</sub>,y<sub>max</sub>);</li> <li>Divide R into an arbitrary number of points. The paper uses 21 as a heuristic (meaning divide the height and width by 20);</li> <li>Clip any points that are outside the polygon;</li> <li>For the remainder find the point that is furthest from any point on the edge;</li> <li>From that point define a new R with smaller intervals and bounds and repeat from step 2 to get to any arbitrary precision answer. The paper reduces R by a factor of the square root of 2.</li> </ol> <p>One note, How to test if a point is inside the polygon or not: The simplest solution to this part of the problem is to cast a ray to the right of the point. If it crosses an odd number of edges, it's within the polygon. If it's an even number, it's outside.</p> <p>Also, as far as testing the distance to any edge there are two cases you need to consider:</p> <ol> <li>The point is perpendicular to a point on that edge (within the bounds of the two vertices); or</li> <li>It isn't.</li> </ol> <p>(2) is easy. The distance to the edge is the minimum of the distances to the two vertices. For (1), the closest point on that edge will be the point that intersects the edge at a 90 degree angle starting from the point you're testing. See <a href="http://geomalgorithms.com/a02-_lines.html" rel="noreferrer">Distance of a Point to a Ray or Segment</a>.</p>
4,066,438
Android WebView, how to handle redirects in app instead of opening a browser
<p>So right now in my app the URL I'm accessing has a redirect, and when this happens the WebView will open a new browser, instead of staying in my app. Is there a way I can change the settings so the View will redirect to the URL like normal, but stay in my app instead of opening a new browser?</p> <p>Edit:</p> <p>I want the redirecting URL, I just don't know how to create it, so the only way to get to that URL is through one that will cause a redirect to the one I want. </p> <p>For example: When you go here: <a href="http://www.amazon.com/gp/aw/s/ref=is_box_/k=9780735622777" rel="noreferrer">http://www.amazon.com/gp/aw/s/ref=is_box_/k=9780735622777</a> notice how it will redirect the URL to the actual product. In my app, if I open it in a new browser, it will do that just fine, however if I keep it in my app with a WebView, it will show up as though it's doing a search for k=9780735622777, like this: <a href="http://www.amazon.com/gp/aw/s/ref=is_s_?k=k%3D9780735622777&amp;x=0&amp;y=0" rel="noreferrer">http://www.amazon.com/gp/aw/s/ref=is_s_?k=k%3D9780735622777&amp;x=0&amp;y=0</a> . OR, it will open the view in the browser and show what is appropriate. However, I want to keep everything in my app.</p>
4,066,497
8
0
null
2010-11-01 03:13:05.59 UTC
44
2022-04-19 12:53:36.083 UTC
2013-07-11 08:48:59.143 UTC
user2571762
null
null
325,400
null
1
140
android|android-webview
176,275
<p>Create a WebViewClient, and override the <a href="http://developer.android.com/reference/android/webkit/WebViewClient.html#shouldOverrideUrlLoading%28android.webkit.WebView,%20java.lang.String%29" rel="noreferrer">shouldOverrideUrlLoading</a> method.</p> <pre><code>webview.setWebViewClient(new WebViewClient() { public boolean shouldOverrideUrlLoading(WebView view, String url){ // do your handling codes here, which url is the requested url // probably you need to open that url rather than redirect: view.loadUrl(url); return false; // then it is not handled by default action } }); </code></pre>
4,298,078
Why we should use PHP?
<p>I have just started to learn HTML, JavaScript and PHP. After studying little, I sometimes think to myself, "why we need PHP"? Whatever we can do using PHP, can be done using Javascript(I think that but I am a noob to this). So why do we use PHP? Can anybody explain to me its use?( I apologize in advance if the question is totally foolish and the answer is very obvious - but as I said, I am noob to web).</p>
4,298,109
10
3
null
2010-11-28 17:43:30.083 UTC
16
2017-12-05 05:56:39.927 UTC
2017-12-05 05:56:39.927 UTC
null
6,908,774
null
417,552
null
1
24
php|javascript|html
32,466
<p>PHP is a server-side scripting language. JavaScript is run client-side.</p> <p>You can for example not do anything database related in JavaScript. Even <em>if</em> there where database libraries written for JavaScript they would be of no use because your server cannot trust database queries done by the client. For example, you cannot delete forum posts client-side because then anybody would be able to delete those posts under the disguise of an administrator.</p> <p>PHP can do <strong>a lot</strong> that JS cannot do. Image resizing, saving files on the server, database queries, e-mailing, PDF generation, secure login systems, RSS parsing, SOAP calls to web services, anything where you cannot trust the client (because the user can change JS code as they want, and there's no way for you to control that).</p> <p>They are two entirely different languages, made for different needs.</p> <p>There are however a few JS servers, which run JavaScript code server-side. <a href="http://nodejs.org">Node.JS</a> is one example of such a system. Then you don't need to learn a new language, but you still need to differentiate what you do in the client from what you do on the server-side.</p>
14,646,856
Download and install JavaFX for Eclipse
<p>I'm an experienced (Java, Eclipse &amp; Maven) developer, and have used a couple of frameworks thus far. Every time I'm trying to start with something new, it seems like there are about a zillion configuration possible for downloading and installing it.</p> <p>I've looked <a href="http://docs.oracle.com/javafx/1.2/gettingstarted/eclipse-plugin/index.html#downloadinfo">here</a> for instructions, and all the near pages, but they seem out dated, the Eclipse plugin path is invalid, and when I install the latest version I've found no the site (2.0.2), it says that I have a newer version installed.</p> <p>Also, the Maven setup in most posts I've read seems obscure.</p> <p><strong>I'm using:</strong></p> <ul> <li>Windows 7</li> <li>Eclipse x64 Indigo</li> <li>JDK x64 1.6.0.24</li> <li>Maven 3.0.3 </li> </ul> <p>And I don't recall installing the JavaFX.</p> <p>What an I missing? Where can I read about the setup in order to start working with this framework?</p>
14,647,111
3
0
null
2013-02-01 12:58:38.11 UTC
3
2018-11-20 11:20:30.187 UTC
null
null
null
null
348,189
null
1
10
java|eclipse|maven|javafx
69,883
<p>JavaFX gets installed if you install the latest JDK 7 from Oracle (co-bundled).</p> <p>You can find the Eclipse plugin here: </p> <p><a href="http://efxclipse.org/">http://efxclipse.org/</a></p> <p>If your're interested in Maven builds: I've recently released an initial version of Drombler FX, a modular RCP for JavaFX based on OSGi and Maven (POM-first):</p> <p><a href="http://puces-blog.blogspot.ch/2012/12/drombler-fx-building-modular-javafx.html">http://puces-blog.blogspot.ch/2012/12/drombler-fx-building-modular-javafx.html</a></p> <p><a href="http://wiki.drombler.org/GettingStarted">http://wiki.drombler.org/GettingStarted</a></p>
14,815,838
webkit / Chrome history.back(-1) onclick vs href
<p>Everybody knows that but I'll repeat the problem:</p> <pre><code>&lt;a href="#" onClick="history.go(-1)"&gt;Back&lt;/a&gt; </code></pre> <p>Will not work in WebKit based browsers (Chrome, Safari, Mxthon, etc.)</p> <p>Another approach (should work) that won't work is:</p> <pre><code>&lt;a href="#" onclick="javascript:window.history.back(-1);"&gt;Back&lt;/a&gt; </code></pre> <p>You could do this - works! (but that's showing JS in url hint)</p> <pre><code>&lt;a href="javascript:window.history.back(-1);"&gt;Back&lt;/a&gt; </code></pre> <p>To use JS in onclick event you could do this (works, but see comments below):</p> <pre><code>&lt;a onclick="javascript:window.history.back(-1);"&gt;Please try again&lt;/a&gt; </code></pre> <p>Missing href will make it work, but then it won't appear as clickable link, you could apply css to make it look like link, apply blue color, underline and cursor hand, but who wants that?</p>
14,815,839
3
3
null
2013-02-11 15:58:32.483 UTC
2
2017-06-12 05:59:13.22 UTC
2013-06-24 20:27:33.06 UTC
null
59,303
null
1,818,723
null
1
18
javascript|google-chrome|onclick|href
48,397
<p>Finally working solution, tested in IE, FF, Safari, Chrome, Opera, Maxthon:</p> <pre><code>&lt;a href="#" onclick="window.history.back();return false;"&gt;Back&lt;/a&gt; </code></pre> <p>Don't forget semicolon after return false;</p>
14,681,012
How to Include OpenSSL in a Qt project
<p>I'm new to Qt, I've done some Googleing and can't find a detailed enough answer.</p> <p>I need to use OpenSSL in my qmake-based Qt project. How do I go about downloading/installing/linking it so I can just do an include statement and use its functions in my code?</p>
14,681,524
5
2
null
2013-02-04 05:44:20.773 UTC
11
2018-08-20 13:20:22.02 UTC
2016-08-08 23:21:32.183 UTC
null
608,639
null
1,374,026
null
1
18
qt|windows-7|linker|openssl
42,614
<p>Assuming Windows, you can download its installation from <a href="http://slproweb.com/products/Win32OpenSSL.html" rel="noreferrer"><strong>Win32 OpenSSL Installation Project page</strong></a>. You can choose one for 64-bit windows developing or for 32-bit. Just run the setup and everything will be done easily. The default installation directory is : <strong>C:\OpenSSL-Win32</strong><br> In <strong>Qt creator</strong>, if you then want to link a library to your project you can just add this line to your .pro file(project file ) : </p> <pre><code>LIBS += -L/path/to -llibname </code></pre> <p>So here's what we do for this library( for example to link ubsec.lib )</p> <pre><code>LIBS += -LC:/OpenSSL-Win32/lib -lubsec </code></pre> <p>Pay attention to <strong>-L</strong> and <strong>-l</strong>.<a href="https://stackoverflow.com/questions/718447/adding-external-library-into-qt-creator-project">See this question</a>. You don't even need to specify .lib at the end of the library name.</p> <p>For including .h files add this line to your .pro file : </p> <pre><code>INCLUDEPATH += C:/OpenSSL-Win32/include </code></pre> <p>after that you can include a file like this :</p> <pre><code>#include &lt;openssl/aes.h&gt; </code></pre>
14,833,070
NSGenericException', reason: 'Unable to install constraint on view
<p>Terminating app due to uncaught exception 'NSGenericException'</p> <blockquote> <p>Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to install constraint on view. Does the constraint reference something from outside the subtree of the view? That's illegal. constraint: view:; layer = ; contentOffset: {0, 0}>'</p> </blockquote>
14,833,369
7
3
null
2013-02-12 12:54:44.347 UTC
4
2017-12-21 06:15:30.663 UTC
2017-12-21 06:15:30.663 UTC
null
4,061,501
null
2,049,753
null
1
31
iphone|objective-c|ios6|xcode4.5
31,987
<p>You need to install the constraint on the "higher" of the two views. A good, general way to do this is like this: </p> <pre><code>NSLayoutConstraint* constraint = ...; NSView* firstView = constraint.firstItem; NSView* secondView = constraint.secondItem; [[firstView ancestorSharedWithView: secondView] addConstraint: constraint]; </code></pre> <p>Just a word of caution: It's good to remember here that constraint attributes are evaluated in the context of the view on which they are added. So for instance, the value of NSLayoutAttributeLeft of viewA, for a constraint installed on viewB, is interpreted in the coordinate space of viewB. For constraints that only reference sibling views or their superview, that fact is largely irrelevant, but there's no restriction that constraints can't reference two views that aren't siblings or direct parents.</p>
14,503,932
How do I package an existing VM that was not created using vagrant up command?
<p>I installed a VirtualBox and then installed a Ubuntu 12.10 Server Base OS in it. I have installed all kinds of php packages and other packages in it. My friends recommended me to use Vagrant so I can share my setup with my team mates easily.</p> <p>Because my current VirtualBox VM was not created using <code>vagrant up</code>, I am not sure how to package it. The <a href="http://docs.vagrantup.com/v1/docs/getting-started/packaging.html">documentation</a> over at Vagrant talks about packaging but starts by saying:</p> <blockquote> <p>Before working through the rest of this page, make sure the virtual environment is built by running vagrant up.</p> </blockquote> <p>In my case, my existing VM was NOT created initially using vagrant up.</p> <p>How do I package my existing VM?</p>
15,050,730
9
0
null
2013-01-24 14:42:39.453 UTC
22
2015-10-18 08:57:39.677 UTC
2013-01-25 11:29:19.557 UTC
null
45,773
null
80,353
null
1
43
virtual-machine|virtualbox|packaging|vagrant
42,805
<p>The important thing to realize (and the vagrant docs are not overly clear on that) is that there are two "flavors" of packaging:</p> <ol> <li>The <a href="http://docs.vagrantup.com/v1/docs/getting-started/packaging.html" rel="noreferrer">packaging guide in "getting started"</a> you are referring to assumes <em>you have started from a vagrant base box</em> and initialized it with <code>vagrant up</code>, which you have not. This allows you to <em>package any customizations you have made to a vagrant base box</em>.</li> <li>If you start from scratch or from a "plain" VirtualBox VM, as you do, you need to create a <a href="http://docs.vagrantup.com/v1/docs/base_boxes.html" rel="noreferrer">vagrant base box</a>. You should be fine following the <a href="http://docs.vagrantup.com/v1/docs/base_boxes.html" rel="noreferrer">guide</a>, which is based on Ubuntu.</li> </ol> <p>There's a <a href="http://pyfunc.blogspot.co.uk/2011/11/creating-base-box-from-scratch-for.html" rel="noreferrer">detailed guide for creating vagrant boxes from scratch</a> using Oracle Enterprise Linux, which might be helpful. You could also try <a href="https://github.com/jedi4ever/veewee" rel="noreferrer">VeeWee</a>.</p> <p>Alternatively, you could start with a <a href="http://vagrantbox.es" rel="noreferrer">Ubuntu 12.10 base box</a> and port your customizations, in which case you could use the simpler first way of packaging.</p> <h3>Update</h3> <p>The above refers to Vagrant 1.0. Things have changed slightly in 1.1 and in particular the docs have been rewritten:</p> <ol> <li>The <code>vagrant package</code> <a href="http://docs.vagrantup.com/v2/cli/package.html" rel="noreferrer">command</a> allows you to <em>package any customizations you have made to an existing vagrant base box</em> in the same way as in 1.0.</li> <li>The <a href="http://docs.vagrantup.com/v1/docs/base_boxes.html" rel="noreferrer">documentation for creating base boxes with VirtualBox</a> has been removed in 1.1, but the <a href="http://docs.vagrantup.com/v2/boxes.html" rel="noreferrer">docs</a> suggest the process has stayed the same, but now an additional <code>metadata.json</code> file <a href="http://docs.vagrantup.com/v2/boxes/format.html" rel="noreferrer">is required</a> as Vagrant 1.1 supports <a href="http://docs.vagrantup.com/v2/providers/" rel="noreferrer">multiple providers</a>.</li> </ol>
14,513,468
Detect decimal separator
<p>I have to detect decimal separator in current windows setting. Im using visual studio 2010, windows form. In particular, if DecimalSeparator is comma, if user input dot in textbox1, I need show zero in textbox2.</p> <p>I tryed with this code, but not works:</p> <pre><code>private void tbxDaConvertire_KeyPress(object sender, KeyPressEventArgs e) { string uiSep = CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator; if (uiSep.Equals(",")) { while (e.KeyChar == (char)46) { tbxConvertito.Text = "0"; } } } </code></pre> <p>I have tryed also this code, but not work:</p> <pre><code>private void tbxDaConvertire_KeyPress(object sender, KeyPressEventArgs e) { string uiSep = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator; if (uiSep.Equals(",")) { if (e.KeyChar == (char)46) { tbxConvertito.Text = "0"; } } } </code></pre>
14,513,803
3
9
null
2013-01-25 00:38:16.697 UTC
7
2022-01-12 16:54:05.427 UTC
2013-01-25 00:51:36.623 UTC
null
1,780,601
null
1,780,601
null
1
59
c#|globalization
90,490
<p>Solution:</p> <pre><code>private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { char a = Convert.ToChar(Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator); if (e.KeyChar == a) { e.Handled = true; textBox1.Text = "0"; } } </code></pre> <p>That way, when you hit <code>.</code> or <code>,</code> you will have a <code>0</code> in your TextBox.</p> <p>EDIT:</p> <p>If you want to insert a <code>0</code> everytime you hit the decimal separator, this is the code:</p> <pre><code>char a = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator); if (e.KeyChar == a) { e.KeyChar = '0'; } </code></pre>
14,614,134
Create array and push into it in one line
<p>The following is just a theoretical JavaScript question. I am curious if the following can be converting into a single statement:</p> <pre><code>if(!window.foo){ window.foo = []; } window.foo.push('bar'); </code></pre> <p>everyone has probably written this code before, but can it be done in one line?<br> At first I thought something like this would work:</p> <pre><code>(window.foo || window.foo = []).push('bar'); </code></pre> <p>but that doesn't work because of an invalid assignment. Next I tried chaining something on the push, but that doesn't work because push does not return the array. </p> <p>Any thoughts on if this can be done in plain JavaScript?<br> (the result by the way should be that <code>window.foo = ['bar']</code>)</p>
14,614,169
4
7
null
2013-01-30 21:28:15.793 UTC
7
2021-11-08 14:44:08.573 UTC
2013-01-30 23:07:54.41 UTC
null
168,175
null
26,188
null
1
61
javascript
30,773
<p>You've got your assignment backwards*. It should be:</p> <pre><code>(window.foo = window.foo || []).push('bar'); </code></pre> <p>The <code>||</code> operator in JavaScript <em>does not return a boolean value</em>. If the left hand side is truthy, it returns the left hand side, otherwise it returns the right hand side.</p> <pre><code>a = a || []; </code></pre> <p>is equivalent to</p> <pre><code>a = a ? a : []; </code></pre> <p>So an alternative way of writing the above is:</p> <pre><code>(window.foo = window.foo ? window.foo : []).push('bar'); </code></pre> <p>* see comments for details</p>
14,391,272
Does constexpr imply inline?
<p>Consider the following inlined function :</p> <pre><code>// Inline specifier version #include&lt;iostream&gt; #include&lt;cstdlib&gt; inline int f(const int x); inline int f(const int x) { return 2*x; } int main(int argc, char* argv[]) { return f(std::atoi(argv[1])); } </code></pre> <p>and the constexpr equivalent version :</p> <pre><code>// Constexpr specifier version #include&lt;iostream&gt; #include&lt;cstdlib&gt; constexpr int f(const int x); constexpr int f(const int x) { return 2*x; } int main(int argc, char* argv[]) { return f(std::atoi(argv[1])); } </code></pre> <p>My question is : does the <code>constexpr</code> specifier imply the <code>inline</code> specifier in the sense that if a non-constant argument is passed to a <code>constexpr</code> function, the compiler will try to <code>inline</code> the function as if the <code>inline</code> specifier was put in its declaration ?</p> <p>Does the C++11 standard guarantee that ?</p>
14,391,320
2
3
null
2013-01-18 01:48:15.663 UTC
17
2021-01-22 08:07:11.513 UTC
null
null
null
null
882,932
null
1
142
c++|c++11|inline|standards-compliance|constexpr
43,801
<p>Yes ([dcl.constexpr], §7.1.5/2 in the C++11 standard): "constexpr functions and constexpr constructors are implicitly inline (7.1.2)." </p> <p>Note, however, that the <code>inline</code> specifier really has <em>very</em> little (if any) effect upon whether a compiler is likely to expand a function inline or not. It does, however, affect the one definition rule, and from that perspective, the compiler is required to follow the same rules for a <code>constexpr</code> function as an <code>inline</code> function.</p> <p>I should also add that regardless of <code>constexpr</code> implying <code>inline</code>, the rules for <code>constexpr</code> functions in C++11 required them to be simple enough that they were often good candidates for inline expansion (the primary exception being those that are recursive). Since then, however, the rules have gotten progressively looser, so <code>constexpr</code> can be applied to substantially larger, more complex functions.</p>
34,437,340
How to disable peek on go to definition
<p>In visual studio when i press F12 (go to definition) on any methods it open in a "peek" kind of window on the right side of the document tabs in fushia/pink like color on the dark theme. The problem is that 99% of the time i need to F12 into 2 or more methods but that window keep being replace by the latest. So i need to remember to click pin for every single time i press F12. I am wondering if i can disable this peek and make F12 open in a normal window like i opened the class.</p> <p>I already disabled the preview class on the project treeview which open any class in the same "peek" tab.</p> <p>I found some help but for VS2013 with powertool but VS2015 these tools are integrated and i didn't found the equivalent option menu.</p> <p>My VS is up to date excluding the latest Azure update which i don't use.</p>
34,437,772
5
1
null
2015-12-23 14:01:41.313 UTC
3
2019-04-12 19:03:44.193 UTC
null
null
null
null
2,748,412
null
1
35
visual-studio-2015
7,949
<p>Check the Visual Studio options:</p> <ul> <li>Disable "Control click shows definitions in Peek" option in: <kbd>Options</kbd>→<kbd>Productivity Power Tools</kbd>→<kbd>Other Extentions</kbd>.</li> <li>Disable "Allow new files to be opened in preview tab" in: <kbd>Options</kbd>→<kbd>Environment</kbd>→<kbd>Tabs and Windows</kbd>.</li> <li>Ensure you have <kbd>F12</kbd> key assigned to <code>Edit.GoToDefinition</code> per <code>Global</code> scope in: <kbd>Options</kbd>→<kbd>Environment</kbd>→<kbd>Keyboard</kbd>.</li> </ul> <p><strong>UPDATE</strong>: It works for Visual Studio 2017 as well.</p>
26,195,243
Creating an Observable List/Collection
<p>I'm trying to create a <code>ChoiceBox</code> in JavaFX 8, which requires a <code>Collection</code>. I can't figure out how to create a <code>Collection</code> though... If I try:</p> <pre><code> ObservableList&lt;String&gt; list = new ObservableList&lt;String&gt;(); </code></pre> <p>I get an error saying I can't instantiate <code>ObservableList</code> because it's abstract. Understandable. If I look at the doc for <code>ObservableList</code> I can see that <code>SortedList implements ObservableList</code>, but I can't do:</p> <pre><code> ObservableList&lt;String&gt; list = new SortedList&lt;String&gt;(); </code></pre> <p>Because there's no applicable constructor. Apparently I need to have an <code>ObservableList</code> to pass to the <code>SortedList</code>, which is odd because I can't create an <code>ObservableList</code>.</p> <pre><code>constructor SortedList.SortedList(ObservableList&lt;? extends String&gt;,Comparator&lt;? super String&gt;) is not applicable (actual and formal argument lists differ in length) constructor SortedList.SortedList(ObservableList&lt;? extends String&gt;) is not applicable (actual and formal argument lists differ in length) </code></pre> <p>I'm not sure how to decipher that. If I try </p> <pre><code> ObservableList&lt;String&gt; list = new SortedList&lt;SortedList&lt;String&gt;&gt;(); //or ObservableList&lt;String&gt; list = new SortedList&lt;ObservableList&lt;String&gt;&gt;(); </code></pre> <p>out of desperation, I get an even more convoluted error.</p> <pre><code> SortedList&lt;String&gt; list = new SortedList&lt;String&gt;(); </code></pre> <p>doesn't work either. Somehow this works (but apparently uses an unsafe operation):</p> <pre><code>ChoiceBox box = new ChoiceBox(FXCollections.observableArrayList("Asparagus", "Beans", "Broccoli", "Cabbage" , "Carrot", "Celery", "Cucumber", "Leek", "Mushroom" , "Pepper", "Radish", "Shallot", "Spinach", "Swede" , "Turnip")); </code></pre> <p>So I tried:</p> <pre><code> ObservableList&lt;string&gt; list = new FXCollections.observableArrayList("Asparagus", "Beans", "Broccoli", "Cabbage" , "Carrot", "Celery", "Cucumber", "Leek", "Mushroom" , "Pepper", "Radish", "Shallot", "Spinach", "Swede" , "Turnip"); </code></pre> <p>But no luck there either. I'm super confused, doing the same thigns over and over in an endless loop of trying to understand this. The documentation I've found shows examples that don't help, or no examples. The official documentation is useless too:</p> <blockquote> <p>Suppose, for example, that you have a Collection c, which may be a List, a Set, or another kind of Collection. This idiom creates a new ArrayList (an implementation of the List interface), initially containing all the elements in c.</p> <pre><code> List&lt;String&gt; list = new ArrayList&lt;String&gt;(c); </code></pre> </blockquote> <p>So to create <code>ArrayList</code>, an implementation of <code>List</code>, I need to have a <code>List</code>. the reason I went to the documentation in the first place was to learn how to make what they're assuming I have. I'm lost. Help?</p>
26,195,354
1
0
null
2014-10-04 17:23:49.32 UTC
16
2018-03-23 03:42:28.367 UTC
2018-03-23 03:42:28.367 UTC
null
4,298,200
null
2,638,976
null
1
39
java|list|collections|interface|javafx
82,105
<p>Use the factory methods in <a href="http://docs.oracle.com/javase/8/javafx/api/javafx/collections/FXCollections.html"><code>FXCollections</code></a>:</p> <pre><code>ObservableList&lt;String&gt; list = FXCollections.observableArrayList(); </code></pre> <p>The unsafe operation in your choice box constructor is because you haven't specified the type for the choice box:</p> <pre><code>ChoiceBox&lt;String&gt; box = new ChoiceBox&lt;&gt;(FXCollections.observableArrayList("Asparagus", "Beans", "Broccoli", "Cabbage" , "Carrot", "Celery", "Cucumber", "Leek", "Mushroom" , "Pepper", "Radish", "Shallot", "Spinach", "Swede" , "Turnip")); </code></pre> <p>and the error from <code>SortedList</code> is because there is no constructor taking no arguments. (Again, refer to the <a href="http://docs.oracle.com/javase/8/javafx/api/javafx/collections/transformation/SortedList.html">javadocs</a>.) There are two constructors: the simplest one takes a reference to an <code>ObservableList</code> (the list for which the sorted list will provide a sorted view). So you would need something like</p> <pre><code>SortedList&lt;String&gt; sortedList = new SortedList&lt;&gt;(list); </code></pre> <p>or </p> <pre><code>SortedList&lt;String&gt; sortedList = new SortedList&lt;&gt;(FXCollections.observableArrayList()); </code></pre>
7,306,616
Bulk Insert with filename parameter
<p>I need to load a couple of thousands of data files into SQL Server table. So I write a stored procedure that receives just one parameter - file name. But.. The following doesn't work.. The "compiler" complains on @FileName parameter.. It wants just plain string.. like 'file.txt'. Thanks in advance.</p> <p>Ilan.</p> <pre><code>BULK INSERT TblValues FROM @FileName WITH ( FIELDTERMINATOR =',', ROWTERMINATOR ='\n' ) </code></pre>
7,306,741
1
3
null
2011-09-05 10:15:16.163 UTC
3
2011-09-05 12:07:16.263 UTC
2011-09-05 10:32:09.4 UTC
null
393,908
null
844,136
null
1
29
sql-server|sql-server-2005|tsql|sql-server-2008|bulkinsert
50,195
<p><a href="http://msdn.microsoft.com/en-us/library/ms188365%28v=SQL.100%29.aspx">The syntax for BULK INSERT statement</a> is : </p> <pre><code>BULK INSERT [ database_name. [ schema_name ] . | schema_name. ] [ table_name | view_name ] FROM 'data_file' [ WITH </code></pre> <p>So, the file name must be a string constant. To solve the problem please use dynamic SQL:</p> <pre><code>DECLARE @sql NVARCHAR(4000) = 'BULK INSERT TblValues FROM ''' + @FileName + ''' WITH ( FIELDTERMINATOR ='','', ROWTERMINATOR =''\n'' )'; EXEC(@sql); </code></pre>
50,293,660
Inserting RecyclerView items at zero position - always stay scrolled to top
<p>I have a pretty standard <code>RecyclerView</code> with a vertical <code>LinearLayoutManager</code>. I keep inserting new items at the top and I'm calling <code>notifyItemInserted(0)</code>.</p> <p><strong>I want the list to stay scrolled to the top</strong>; to always display the 0th position.</p> <p>From my requirement's point of view, the <code>LayoutManager</code> behaves differently based on the number of items.</p> <p>While all items fit on the screen, it looks and behaves as I expect: The <strong>new item always appears on top and shifts everything</strong> below it.</p> <p><a href="https://i.stack.imgur.com/reTZu.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/reTZu.gif" alt="Behavior with few items: Addition shifts other items down, first (newest) item is always visible"></a></p> <p>However, as soon as the no. of items exceeds the RecyclerView's bounds, <strong>new items are added above</strong> the currently visible one, but the <strong>visible items stay in view</strong>. The user has to scroll to see the newest item.</p> <p><a href="https://i.stack.imgur.com/1IW9g.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/1IW9g.gif" alt="Behavior with many items: New items are added above the top boundary, user has to scroll to reveal them"></a></p> <p>This behavior is totally understandable and fine for many applications, but not for a "live feed", where seeing the most recent thing is more important than "not distracting" the user with auto-scrolls.</p> <hr> <p>I know this question is almost a duplicate of <a href="https://stackoverflow.com/questions/38850591/adding-new-item-to-the-top-of-the-recyclerview">Adding new item to the top of the RecyclerView</a>... but all of the proposed answers are mere <strong>workarounds</strong> (most of them quite good, admittedly).</p> <p>I'm looking for a way to actually <strong>change this behavior</strong>. I want the LayoutManager to <strong>act exactly the same, no matter the number of items</strong>. I want it to always shift all of the items (just like it does for the first few additions), not to stop shifting items at some point, and compensate by smooth-scrolling the list to the top.</p> <p>Basically, no <code>smoothScrollToPosition</code>, no <code>RecyclerView.SmoothScroller</code>. Subclassing <code>LinearLayoutManager</code> is fine. I'm already digging through its code, but without any luck so far, so I decided to ask in case someone already dealt with this. Thanks for any ideas!</p> <hr> <p><strong>EDIT:</strong> To clarify why I'm dismissing answers from the linked question: Mostly I'm concerned about animation smoothness.</p> <p>Notice in the first GIF where <code>ItemAnimator</code> is moving other items while adding the new one, both fade-in and move animations have the same duration. But when I'm "moving" the items by smooth scrolling, I <strong>cannot easily control the speed of the scroll</strong>. Even with default <code>ItemAnimator</code> durations, this doesn't look as good, but in my particular case, I even needed to slow down the <code>ItemAnimator</code> durations, which makes it even worse:</p> <p><a href="https://i.stack.imgur.com/NeUuj.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/NeUuj.gif" alt="Insert &quot;fixed&quot; with smooth scroll + ItemAnimator durations increased"></a></p>
50,308,230
5
1
null
2018-05-11 13:40:38.417 UTC
7
2021-04-02 11:55:56.963 UTC
2018-05-11 14:52:23.227 UTC
null
1,590,479
null
1,590,479
null
1
28
android|android-layout|android-recyclerview
7,482
<p><em>Although I wrote this answer and this is the accepted solution, I suggest a look at the other later answers to see if they work for you before attempting this.</em></p> <hr /> <p>When an item is added to the top of the <code>RecyclerView</code> and the item can fit onto the screen, the item is attached to a view holder and <code>RecyclerView</code> undergoes an animation phase to move items down to display the new item at the top.</p> <p>If the new item cannot be displayed without scrolling, a view holder is not created so there is nothing to animate. The only way to get the new item onto the screen when this happens is to scroll which causes the view holder to be created so the view can be laid out on the screen. (There does seem to be an edge case where the view is partially displayed and a view holder is created, but I will ignore this particular instance since it is not germane.)</p> <p>So, the issue is that two different actions, animation of an added view and scrolling of an added view, must be made to look the same to the user. We could dive into the underlying code and figure out exactly what is going on in terms of view holder creation, animation timing, etc. But, even if we can duplicate the actions, it can break if the underlying code changes. This is what you are resisting.</p> <p>An alternative is to add a header at position zero of the <code>RecyclerView</code>. You will always see the animation when this header is displayed and new items are added to position 1. If you don't want a header, you can make it zero height and it will not display. The following video shows this technique:</p> <p><a href="https://i.stack.imgur.com/1o6uO.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1o6uO.gif" alt="[video]" /></a></p> <p>This is the code for the demo. It simply adds a dummy entry at position 0 of the items. If a dummy entry is not to your liking, there are other ways to approach this. You can search for ways to add headers to <code>RecyclerView</code>.</p> <p><em>(If you do use a scrollbar, it will misbehave as you can probably tell from the demo. To fix this 100%, you will have to take over a lot of the scrollbar height and placement computation. The custom <code>computeVerticalScrollOffset()</code> for the <code>LinearLayoutManager</code> takes care of placing the scrollbar at the top when appropriate. (Code was introduced after video taken.) The scrollbar, however, jumps when scrolling down. A better placement computation would take care of this problem. See <a href="https://stackoverflow.com/questions/46033473/recyclerview-with-items-of-different-height-scrollbar">this Stack Overflow question</a> for more information on scrollbars in the context of varying height items.)</em></p> <p><strong>MainActivity.java</strong></p> <pre><code>public class MainActivity extends AppCompatActivity implements View.OnClickListener { private TheAdapter mAdapter; private final ArrayList&lt;String&gt; mItems = new ArrayList&lt;&gt;(); private int mItemCount = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView); LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) { @Override public int computeVerticalScrollOffset(RecyclerView.State state) { if (findFirstCompletelyVisibleItemPosition() == 0) { // Force scrollbar to top of range. When scrolling down, the scrollbar // will jump since RecyclerView seems to assume the same height for // all items. return 0; } else { return super.computeVerticalScrollOffset(state); } } }; recyclerView.setLayoutManager(layoutManager); for (mItemCount = 0; mItemCount &lt; 6; mItemCount++) { mItems.add(0, &quot;Item # &quot; + mItemCount); } // Create a dummy entry that is just a placeholder. mItems.add(0, &quot;Dummy item that won't display&quot;); mAdapter = new TheAdapter(mItems); recyclerView.setAdapter(mAdapter); } @Override public void onClick(View view) { // Always at to position #1 to let animation occur. mItems.add(1, &quot;Item # &quot; + mItemCount++); mAdapter.notifyItemInserted(1); } } </code></pre> <p><strong>TheAdapter.java</strong></p> <pre><code>class TheAdapter extends RecyclerView.Adapter&lt;TheAdapter.ItemHolder&gt; { private ArrayList&lt;String&gt; mData; public TheAdapter(ArrayList&lt;String&gt; data) { mData = data; } @Override public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view; if (viewType == 0) { // Create a zero-height view that will sit at the top of the RecyclerView to force // animations when items are added below it. view = new Space(parent.getContext()); view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0)); } else { view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.list_item, parent, false); } return new ItemHolder(view); } @Override public void onBindViewHolder(final ItemHolder holder, int position) { if (position == 0) { return; } holder.mTextView.setText(mData.get(position)); } @Override public int getItemViewType(int position) { return (position == 0) ? 0 : 1; } @Override public int getItemCount() { return mData.size(); } public static class ItemHolder extends RecyclerView.ViewHolder { private TextView mTextView; public ItemHolder(View itemView) { super(itemView); mTextView = (TextView) itemView.findViewById(R.id.textView); } } } </code></pre> <p><strong>activity_main.xml</strong></p> <pre><code>&lt;android.support.constraint.ConstraintLayout android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; android:orientation=&quot;vertical&quot; tools:context=&quot;.MainActivity&quot;&gt; &lt;android.support.v7.widget.RecyclerView android:id=&quot;@+id/recyclerView&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;0dp&quot; android:scrollbars=&quot;vertical&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/button&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt; &lt;Button android:id=&quot;@+id/button&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginBottom=&quot;8dp&quot; android:layout_marginEnd=&quot;8dp&quot; android:layout_marginStart=&quot;8dp&quot; android:text=&quot;Button&quot; android:onClick=&quot;onClick&quot; app:layout_constraintBottom_toBottomOf=&quot;parent&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; /&gt; &lt;/android.support.constraint.ConstraintLayout&gt; </code></pre> <p><strong>list_item.xml</strong></p> <pre><code>&lt;LinearLayout android:id=&quot;@+id/list_item&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginTop=&quot;16dp&quot; android:orientation=&quot;horizontal&quot;&gt; &lt;View android:id=&quot;@+id/box&quot; android:layout_width=&quot;50dp&quot; android:layout_height=&quot;50dp&quot; android:layout_marginStart=&quot;16dp&quot; android:background=&quot;@android:color/holo_green_light&quot; app:layout_constraintBottom_toBottomOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt; &lt;TextView android:id=&quot;@+id/textView&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginStart=&quot;16dp&quot; android:textSize=&quot;24sp&quot; app:layout_constraintBottom_toBottomOf=&quot;parent&quot; app:layout_constraintStart_toEndOf=&quot;@id/box&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot; tools:text=&quot;TextView&quot; /&gt; &lt;/LinearLayout&gt; </code></pre>
48,600,034
reCAPTCHA:"ERROR for site owner: Invalid site key"
<p>I tried to set up reCAPTCHA, on my page by following the instructions <a href="https://developers.google.com/recaptcha/intro" rel="noreferrer">here</a>. I signed up for an API key pair and was issued a public key and a private key. It was not clear, to me, how the private key should be used and I could not find more information about it. It does not appear to be used on the page where reCAPTCHA is called.</p> <p>I edited my page and put </p> <pre><code>&lt;script src='https://www.google.com/recaptcha/api.js'&gt;&lt;/script&gt; </code></pre> <p>before the closing <code>&lt;/head&gt;</code> tag on my HTML template.</p> <p>I also put </p> <pre><code>&lt;div class="g-recaptcha" data-sitekey="my-public-key"&gt;&lt;/div&gt; </code></pre> <p>where I want my reCAPTCHA widget to appear.</p> <p>When I load my page, I get the message</p> <blockquote> <p>Cannot contact reCAPTCHA. Check your connection and try again.</p> </blockquote> <p>I also see the reCAPTCHA widget with the text</p> <blockquote> <p>ERROR for site owner: Invalid site key</p> </blockquote> <p>I have checked similar questions such as <a href="https://stackoverflow.com/questions/47218606/error-for-the-site-owner-google-site-owner">this</a>, where the answer says the key is probably invalid but I have just generated it. I also saw <a href="https://stackoverflow.com/questions/44631918/error-for-site-owner-invalid-site-key">this</a> but I did not disable </p> <pre><code>Verify the origin of reCAPTCHA solutions </code></pre>
48,939,902
15
0
null
2018-02-03 17:28:34.227 UTC
5
2022-09-20 23:35:44.643 UTC
2018-02-04 12:28:57.533 UTC
null
1,016,716
null
1,114,136
null
1
47
recaptcha
133,638
<p>You need to ensure your site is added in the domains section of the google reCAPTCHA page where you generated the API key and save. Then test again. That worked for me.</p>
27,690,834
How to put reload option in ui-sref markup
<p>How can I specify the <code>reload</code> option in a <code>ui-sref</code> markup? All the examples I see use the javascript function directly.</p> <pre><code>&lt;a ui-sref="app.editPost({new:true}, {reload:true})"&gt;new post&lt;/a&gt; </code></pre> <p>Doesn't seem to work. Do I have to create a scope controller function to wrap that <code>reload</code> option instead?</p> <p>I've also tried some answers below and it doesn't seem to work with the Ionic framework. Link to code pen sample below:</p> <p><a href="http://codepen.io/anon/pen/LERqeb" rel="noreferrer">http://codepen.io/anon/pen/LERqeb</a></p>
27,690,880
1
0
null
2014-12-29 14:35:30.73 UTC
3
2020-01-29 05:33:29.37 UTC
2015-12-12 07:53:31.67 UTC
null
2,405,040
null
611,750
null
1
29
javascript|angularjs|ionic-framework|angular-ui-router
27,200
<p>Use <code>ui-sref-opts</code>. Here you go:</p> <pre class="lang-html prettyprint-override"><code>&lt;a ui-sref="app.editPost({new:true})" ui-sref-opts="{reload: true, notify: true}"&gt;new post&lt;/a&gt; </code></pre> <p><a href="https://ui-router.github.io/ng1/docs/0.3.1/index.html#/api/ui.router.state.directive:ui-sref" rel="nofollow noreferrer">https://ui-router.github.io/ng1/docs/0.3.1/index.html#/api/ui.router.state.directive:ui-sref</a></p>
36,064,976
using Doxygen in read-the-docs
<p>I have written the documentation for a medium sized C++ piece of software using Doxygen together with Markdown. I am quite happy with it, as after changing the xml layer I ended up with something like that: <a href="http://docs.mitk.org/nightly/index.html" rel="noreferrer">http://docs.mitk.org/nightly/index.html</a></p> <p>I would like to bring this documentation online, ideally using something like ReadtheDocs, where the documentation would be automatically built after a "git commit", and hosted to be browsed. </p> <p>ReadtheDocs looks like the ideal site but uses Sphinx and reStructuredText as defaults. Doxygen can be used too, but AFAIK only through Breathe. Going through that route essentially means that I would need to re-structure all the documentation if I don't want to dump all the API documentation into a single page (<a href="http://librelist.com/browser//breathe/2011/8/6/fwd-guidance-for-usage-breathe-with-existing-doxygen-set-up-on-a-large-project/#cab3f36b1e4bb2294e2507acad71775f" rel="noreferrer">http://librelist.com/browser//breathe/2011/8/6/fwd-guidance-for-usage-breathe-with-existing-doxygen-set-up-on-a-large-project/#cab3f36b1e4bb2294e2507acad71775f</a>). </p> <p>Paradoxically, Doxygen is installed in the read-the-docs server, but after struggling I could not find a workaround to skip its Sphinx or Mkdocs. </p>
41,199,722
2
0
null
2016-03-17 15:27:43.6 UTC
16
2021-07-31 14:55:29.33 UTC
2016-12-17 14:47:27.74 UTC
null
366,904
null
6,077,773
null
1
19
doxygen|read-the-docs
9,253
<p>I've tried the following solution to use Doxygen on Read The Docs and it seems to work:</p> <ol> <li>set up empty sphinx project (refer to official sphinx doc),</li> <li>in sphinx conf.py add command to build doxygen documentation,</li> <li>use conf.py <em>html_extra_path</em> config directive to overwrite generated doxygen documentation over generated sphinx documentation.</li> </ol> <p>I've tested this with following source tree:</p> <pre><code>.../doc/Doxyfile /build/html /sphinx/conf.py /sphinx/index.rst /sphinx/... </code></pre> <p>Some explanation:</p> <ol> <li>in my setup doxygen generates its documentation in "doc/build/html",</li> <li>ReadTheDocs runs its commands in directory where it finds conf.py file.</li> </ol> <p>What to do:</p> <ol> <li><p>add following lines in conf.py to generate doxygen docs:</p> <pre><code> import subprocess subprocess.call('cd .. ; doxygen', shell=True) </code></pre></li> <li><p>update conf.py <em>html_extra_path</em> directive to:</p> <pre><code> html_extra_path = ['../build/html'] </code></pre></li> </ol> <p>In this configuration ReadTheDocs should properly generate and store Doxygen html documentation.</p> <p>todo:</p> <ul> <li>other documentation formats, for example: pdf.</li> </ul>
35,815,850
Getting imported targets through `find_package`?
<p>The <a href="http://doc.qt.io/qt-5/cmake-manual.html" rel="noreferrer">CMake manual of Qt 5</a> uses <code>find_package</code> and says:</p> <blockquote> <p>Imported targets are created for each Qt module. Imported target names should be preferred instead of using a variable like <code>Qt5&lt;Module&gt;_LIBRARIES</code> in CMake commands such as target_link_libraries.</p> </blockquote> <p>Is it special for Qt or does <code>find_package</code> generate <em>imported targets</em> for all libraries? The <a href="https://cmake.org/cmake/help/v3.0/command/find_package.html" rel="noreferrer">documentation of <code>find_package</code> in CMake 3.0</a> says:</p> <blockquote> <p>When the package is found package-specific information is provided through variables and Imported Targets documented by the package itself.</p> </blockquote> <p>And the <a href="https://cmake.org/cmake/help/v3.0/manual/cmake-packages.7.html" rel="noreferrer">manual for cmake-packages</a> says:</p> <blockquote> <p>The result of using <code>find_package</code> is either a set of IMPORTED targets, or a set of variables corresponding to build-relevant information.</p> </blockquote> <p>But I did not see another <code>FindXXX.cmake</code>-script where the documentation says that a <em>imported target</em> is created.</p>
35,840,894
2
0
null
2016-03-05 15:21:42.937 UTC
9
2022-09-17 23:23:33.053 UTC
null
null
null
null
4,967,497
null
1
14
cmake
12,594
<p><code>find_package</code> is a two-headed beast these days:</p> <blockquote> <p>CMake provides direct support for two forms of packages, <a href="https://cmake.org/cmake/help/latest/manual/cmake-packages.7.html" rel="nofollow noreferrer">Config-file Packages</a> and <a href="https://cmake.org/cmake/help/latest/manual/cmake-packages.7.html#find-module-packages" rel="nofollow noreferrer">Find-module Packages</a></p> </blockquote> <p><a href="https://cmake.org/cmake/help/latest/manual/cmake-packages.7.html" rel="nofollow noreferrer">Source</a></p> <p>Now, what does that actually mean?</p> <p><strong>Find-module packages</strong> are the ones you are probably most familiar with. They execute a script of CMake code (such as <a href="https://github.com/Kitware/CMake/blob/master/Modules/FindZLIB.cmake" rel="nofollow noreferrer">this one</a>) that does a bunch of calls to functions like <a href="https://cmake.org/cmake/help/latest/command/find_library.html" rel="nofollow noreferrer"><code>find_library</code></a> and <a href="https://cmake.org/cmake/help/latest/command/find_path.html" rel="nofollow noreferrer"><code>find_path</code></a> to figure out where to locate a library.</p> <p>The big advantage of this approach is that it is extremely generic. As long as there is something on the filesystem, we can find it. The big downside is that it often provides little more information than the physical location of that something. That is, the result of a find-module operation is typically just a bunch of filesystem paths. This means that modelling stuff like transitive dependencies or multiple build configurations is rather difficult.</p> <p>This becomes especially painful if the thing you are trying to find has <em>itself</em> been built with CMake. In that case, you already have a bunch of stuff modeled in your build scripts, which you now need to painstakingly reconstruct for the find script, so that it becomes available to downstream projects.</p> <p>This is where <strong>config-file packages</strong> shine. Unlike find-modules, the result of running the script is not just a bunch of paths, but it instead creates fully functional CMake targets. To the dependent project it looks like the dependencies have been built as part of that same project.</p> <p>This allows to transport much more information in a very convenient way. The obvious downside is that config-file scripts are much more complex than find-scripts. Hence you do not want to write them yourself, but have CMake generate them for you. Or rather have the dependency provide a config-file as part of its deployment which you can then simply load with a <code>find_package</code> call. And that is exactly what Qt5 does.</p> <p>This also means, if your own project is a library, consider <a href="https://cmake.org/cmake/help/latest/manual/cmake-packages.7.html#creating-packages" rel="nofollow noreferrer">generating a config file as part of the build process</a>. It's not the most straightforward feature of CMake, but the results are pretty powerful.</p> <p>Here is a quick comparison of how the two approaches typically look like in CMake code:</p> <p><em>Find-module style</em></p> <pre><code>find_package(foo) target_link_libraries(bar ${FOO_LIBRARIES}) target_include_directories(bar ${FOO_INCLUDE_DIR}) # [...] potentially lots of other stuff that has to be set manually </code></pre> <p><em>Config-file style</em></p> <pre><code>find_package(foo) target_link_libraries(bar foo) # magic! </code></pre> <p><strong>tl;dr</strong>: Always prefer config-file packages if the dependency provides them. If not, use a find-script instead.</p>
63,314,082
Flutter - How to make a custom TabBar
<p><a href="https://i.stack.imgur.com/IpnYB.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/IpnYB.jpg" alt="My Image" /></a></p> <p>This is the output that I want. I am still new in flutter so can anyone let me know if there is already a widget for this kind of switch or how should I make one ?? Also, I want the data shown below this button to change if I choose the other button but I guess that's obvious.</p> <p>Thanks in advance.</p>
63,319,363
4
0
null
2020-08-08 09:58:36.433 UTC
8
2021-09-29 09:36:40.417 UTC
2020-08-10 11:33:16.783 UTC
null
9,902,765
null
9,451,058
null
1
28
flutter|dart|flutter-layout
33,853
<p>You can use the <code>TabBar</code> widget to achieve this. I added a full example demonstrating how you can create this using the <code>TabBar</code> widget:</p> <p><em>CODE</em></p> <pre><code>class StackOver extends StatefulWidget { @override _StackOverState createState() =&gt; _StackOverState(); } class _StackOverState extends State&lt;StackOver&gt; with SingleTickerProviderStateMixin { TabController _tabController; @override void initState() { _tabController = TabController(length: 2, vsync: this); super.initState(); } @override void dispose() { super.dispose(); _tabController.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( 'Tab bar', ), ), body: Padding( padding: const EdgeInsets.all(8.0), child: Column( children: [ // give the tab bar a height [can change hheight to preferred height] Container( height: 45, decoration: BoxDecoration( color: Colors.grey[300], borderRadius: BorderRadius.circular( 25.0, ), ), child: TabBar( controller: _tabController, // give the indicator a decoration (color and border radius) indicator: BoxDecoration( borderRadius: BorderRadius.circular( 25.0, ), color: Colors.green, ), labelColor: Colors.white, unselectedLabelColor: Colors.black, tabs: [ // first tab [you can add an icon using the icon property] Tab( text: 'Place Bid', ), // second tab [you can add an icon using the icon property] Tab( text: 'Buy Now', ), ], ), ), // tab bar view here Expanded( child: TabBarView( controller: _tabController, children: [ // first tab bar view widget Center( child: Text( 'Place Bid', style: TextStyle( fontSize: 25, fontWeight: FontWeight.w600, ), ), ), // second tab bar view widget Center( child: Text( 'Buy Now', style: TextStyle( fontSize: 25, fontWeight: FontWeight.w600, ), ), ), ], ), ), ], ), ), ); } } </code></pre> <p><em>OUTPUT</em> <a href="https://i.stack.imgur.com/M1XAC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/M1XAC.png" alt="output" /></a></p>
35,158,215
Rename file in DocumentDirectory
<p>I have a PDF file in my <code>DocumentDirectory</code>. </p> <p>I want the user to be able to rename this PDF file to something else if they choose to. </p> <p>I will have a <code>UIButton</code> to start this process. The new name will come from a <code>UITextField</code>. </p> <p>How do I do this? I'm new to Swift and have only found Objective-C info on this and am having a hard time converting it.</p> <p>An example of the file location is:</p> <blockquote> <p>/var/mobile/Containers/Data/Application/39E030E3-6DA1-45FF-BF93-6068B3BDCE89/Documents/Restaurant.pdf</p> </blockquote> <p>I have this code to see check if the file exists or not:</p> <pre><code> var name = selectedItem.adjustedName // Search path for file name specified and assign to variable let getPDFPath = paths.stringByAppendingPathComponent("\(name).pdf") let checkValidation = NSFileManager.defaultManager() // If it exists, delete it, otherwise print error to log if (checkValidation.fileExistsAtPath(getPDFPath)) { print("FILE AVAILABLE: \(name).pdf") } else { print("FILE NOT AVAILABLE: \(name).pdf") } </code></pre>
35,158,471
3
0
null
2016-02-02 16:05:15.663 UTC
5
2020-08-31 21:32:17.653 UTC
2016-11-03 19:08:20.557 UTC
null
2,227,743
null
4,318,303
null
1
33
ios|swift|file-rename
24,348
<p>To rename a file you can use NSFileManager's <code>moveItemAtURL</code>.</p> <p>Moving the file with <code>moveItemAtURL</code> at the same location but with two different file names is the same operation as "renaming".</p> <p>Simple example:</p> <p><strong>Swift 2</strong></p> <pre><code>do { let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] let documentDirectory = NSURL(fileURLWithPath: path) let originPath = documentDirectory.URLByAppendingPathComponent("currentname.pdf") let destinationPath = documentDirectory.URLByAppendingPathComponent("newname.pdf") try NSFileManager.defaultManager().moveItemAtURL(originPath, toURL: destinationPath) } catch let error as NSError { print(error) } </code></pre> <p><strong>Swift 3</strong></p> <pre><code>do { let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let documentDirectory = URL(fileURLWithPath: path) let originPath = documentDirectory.appendingPathComponent("currentname.pdf") let destinationPath = documentDirectory.appendingPathComponent("newname.pdf") try FileManager.default.moveItem(at: originPath, to: destinationPath) } catch { print(error) } </code></pre>
35,036,126
Difference between a -= b and a = a - b in Python
<p>I have recently applied <a href="https://stackoverflow.com/questions/30379311/fast-way-to-take-average-of-every-n-rows-in-a-npy-array">this</a> solution for averaging every N rows of matrix. Although the solution works in general I had problems when applied to a 7x1 array. I have noticed that the problem is when using the <code>-=</code> operator. To make a small example:</p> <pre><code>import numpy as np a = np.array([1,2,3]) b = np.copy(a) a[1:] -= a[:-1] b[1:] = b[1:] - b[:-1] print a print b </code></pre> <p>which outputs:</p> <pre><code>[1 1 2] [1 1 1] </code></pre> <p>So, in the case of an array <code>a -= b</code> produces a different result than <code>a = a - b</code>. I thought until now that these two ways are exactly the same. What is the difference?</p> <p>How come the method I am mentioning for summing every N rows in a matrix is working e.g. for a 7x4 matrix but not for a 7x1 array?</p>
35,036,528
3
0
null
2016-01-27 11:29:43.75 UTC
17
2017-07-18 12:49:25.827 UTC
2017-07-18 12:49:25.827 UTC
null
3,169,567
null
3,169,567
null
1
91
python|arrays|numpy|variable-assignment|in-place
7,976
<p><em>Note: using in-place operations on NumPy arrays that share memory in no longer a problem in version 1.13.0 onward (see details <a href="https://github.com/numpy/numpy/pull/8043" rel="nofollow noreferrer">here</a>). The two operation will produce the same result. This answer only applies to earlier versions of NumPy.</em></p> <hr> <p>Mutating arrays while they're being used in computations can lead to unexpected results!</p> <p>In the example in the question, subtraction with <code>-=</code> modifies the second element of <code>a</code> and then immediately uses that <em>modified</em> second element in the operation on the third element of <code>a</code>.</p> <p>Here is what happens with <code>a[1:] -= a[:-1]</code> step by step:</p> <ul> <li><p><code>a</code> is the array with the data <code>[1, 2, 3]</code>.</p></li> <li><p>We have two views onto this data: <code>a[1:]</code> is <code>[2, 3]</code>, and <code>a[:-1]</code> is <code>[1, 2]</code>.</p></li> <li><p>The in-place subtraction <code>-=</code> begins. The first element of <code>a[:-1]</code>, 1, is subtracted from the first element of <code>a[1:]</code>. This has modified <code>a</code> to be <code>[1, 1, 3]</code>. Now we have that <code>a[1:]</code> is a view of the data <code>[1, 3]</code>, and <code>a[:-1]</code> is a view of the data <code>[1, 1]</code> (the second element of array <code>a</code> has been changed).</p></li> <li><p><code>a[:-1]</code> is now <code>[1, 1]</code> and NumPy must now subtract its second element <em>which is 1</em> (not 2 anymore!) from the second element of <code>a[1:]</code>. This makes <code>a[1:]</code> a view of the values <code>[1, 2]</code>.</p></li> <li><p><code>a</code> is now an array with the values <code>[1, 1, 2]</code>.</p></li> </ul> <p><code>b[1:] = b[1:] - b[:-1]</code> does not have this problem because <code>b[1:] - b[:-1]</code> creates a <em>new</em> array first and then assigns the values in this array to <code>b[1:]</code>. It does not modify <code>b</code> itself during the subtraction, so the views <code>b[1:]</code> and <code>b[:-1]</code> do not change.</p> <hr> <p>The general advice is to avoid modifying one view inplace with another if they overlap. This includes the operators <code>-=</code>, <code>*=</code>, etc. and using the <code>out</code> parameter in universal functions (like <code>np.subtract</code> and <code>np.multiply</code>) to write back to one of the arrays.</p>
9,372,033
How do i pass parameters that is input textbox value to ajax in jQuery
<p>My Ajax code </p> <pre><code>$(document).ready(function() { $("#sub").click(function() { $.ajax({ type: "POST", url: "jqueryphp.php", data: "txt1=" + txt1, success: function(result) { $("div").html(result); } }); }); });​ </code></pre> <p>This is the form code . I want to pass txt1 value to Ajax</p> <pre><code>&lt;input type="text" name="txt1" id="txt1" /&gt;&lt;br&gt; &lt;input type="button" name="sub" id="sub" value="click Me" /&gt; </code></pre> <p>I want to pass <strong>txt1</strong> value to my php page using this Ajax function. </p> <p>Please tell me what exactly will come in the data attribute of Ajax</p>
9,372,087
2
0
null
2012-02-21 04:08:00.95 UTC
1
2019-03-31 15:04:15.807 UTC
2019-03-31 15:04:15.807 UTC
null
7,079,025
null
1,205,245
null
1
0
php|javascript|jquery|ajax|parameters
38,894
<p>Send data as an object instead of a string and to retreive the value of the text field, use val():</p> <pre><code>$(document).ready(function() { $("#sub").click(function() { $.ajax({ type: "POST", url: "jqueryphp.php", data: { txt1: $("#txt1").val() }, success: function(result) { $("div").html(result); } }); }); });​ </code></pre> <p><a href="http://api.jquery.com/val/" rel="noreferrer">http://api.jquery.com/val/</a></p>