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,361,309 | jQuery - resizing image to fit div | <p>I have divs varying in height and width and wish for my images to be automatically resized to fill these divs 100%, and then of course centred.</p>
<p>At the moment my images are set to width 100% and then using the jQuery below centred, but this only works for images where the height are more than the div once resized.. how would I make it 100% for both height and width and center also.. completely filling the div (even if this means stretching the image)!</p>
<p>Thanks.</p>
<pre><code>$('img.shelf-img').each(function(i, item) {
var img_height = $(item).height();
var top_margin = -(img_height / 2);
$(item).css({
'top': '50%',
'margin-top': top_margin
});
});
</code></pre> | 19,361,471 | 2 | 3 | null | 2013-10-14 13:25:27.337 UTC | 4 | 2013-10-14 16:05:34.057 UTC | null | null | null | null | 2,339,984 | null | 1 | 7 | javascript|jquery|html|css | 47,875 | <p>Use CSS to set both the Width and Height of the image to 100% and the image will be automatically stretched to fill the containing div, without the need for jquery. </p>
<p>Also, you will not need to center the image as it will already be stretched to fill the div (centered with zero margins).</p>
<p>HTML:</p>
<pre><code><div id="containingDiv">
<img src="">
</div>
</code></pre>
<p>CSS:</p>
<pre><code>#containingDiv{
width: 200px;
height: 100px;
}
#containingDiv img{
width: 100%;
height: 100%;
}
</code></pre>
<p>That way, if your users have javascript disabled, the image will still be stretched to fill the entire div width/height.</p>
<p>OR</p>
<p>The JQuery way (SHRINK/STRETCH TO FIT - INCLUDES WHITESPACE):</p>
<pre><code>$('img.shelf-img').each(function(i, item) {
var img_height = $(item).height();
var div_height = $(item).parent().height();
if(img_height<div_height){
//IMAGE IS SHORTER THAN CONTAINER HEIGHT - CENTER IT VERTICALLY
var newMargin = (div_height-img_height)/2+'px';
$(item).css({'margin-top': newMargin });
}else if(img_height>div_height){
//IMAGE IS GREATER THAN CONTAINER HEIGHT - REDUCE HEIGHT TO CONTAINER MAX - SET WIDTH TO AUTO
$(item).css({'width': 'auto', 'height': '100%'});
//CENTER IT HORIZONTALLY
var img_width = $(item).width();
var div_width = $(item).parent().width();
var newMargin = (div_width-img_width)/2+'px';
$(item).css({'margin-left': newMargin});
}
});
</code></pre>
<p>The JQuery way - CROP TO FIT (NO WHITESPACE):</p>
<pre><code>$('img.shelf-img').each(function(i, item) {
var img_height = $(item).height();
var div_height = $(item).parent().height();
if(img_height<div_height){
//INCREASE HEIGHT OF IMAGE TO MATCH CONTAINER
$(item).css({'width': 'auto', 'height': div_height });
//GET THE NEW WIDTH AFTER RESIZE
var img_width = $(item).width();
//GET THE PARENT WIDTH
var div_width = $(item).parent().width();
//GET THE NEW HORIZONTAL MARGIN
var newMargin = (div_width-img_width)/2+'px';
//SET THE NEW HORIZONTAL MARGIN (EXCESS IMAGE WIDTH IS CROPPED)
$(item).css({'margin-left': newMargin });
}else{
//CENTER IT VERTICALLY (EXCESS IMAGE HEIGHT IS CROPPED)
var newMargin = (div_height-img_height)/2+'px';
$(item).css({'margin-top': newMargin});
}
});
</code></pre> |
19,338,323 | How to place a div below another div? | <p>I have a <code>#slider</code> div with an image. After that, I have a <code>#content</code> div which has text. I have tried <code>position:relative</code> so I think it should come after the previous div, I mean <code>#slider</code> but here it is not coming that way.</p>
<p>What is the problem here? How to overcome it?</p>
<p><strong>HTML</strong></p>
<pre><code><div id="slider">
<img src="http://oi43.tinypic.com/25k319l.jpg"/>
</div>
<div id="content">
<div id="text">
sample text
</div>
</div>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>#slider {
position:absolute;
left:0;
height:400px;
}
#slider img {
width:100%;
}
#content {
position:relative;
}
#content #text {
position:relative;
width:950px;
height:215px;
color:red;
}
</code></pre>
<p><a href="http://jsfiddle.net/CaZY7/" rel="noreferrer">JSFIDDLE</a></p> | 19,338,426 | 2 | 3 | null | 2013-10-12 19:31:24.42 UTC | 2 | 2020-03-07 14:48:04.32 UTC | 2019-06-20 09:50:04.367 UTC | null | 598,857 | null | 2,714,971 | null | 1 | 34 | html|css | 179,792 | <p>You have set <code>#slider</code> as <code>absolute</code>, which means that it "is positioned relative to the nearest positioned ancestor" (confusing, right?). Meanwhile, <code>#content</code> div is placed relative, which means "relative to its normal position". So the position of the 2 divs is not related.</p>
<p>You can read about CSS positioning <a href="https://www.w3schools.com/css/css_positioning.asp" rel="noreferrer">here</a></p>
<p>If you set both to <code>relative</code>, the divs will be one after the other, as shown here:</p>
<pre><code>#slider {
position:relative;
left:0;
height:400px;
border-style:solid;
border-width:5px;
}
#slider img {
width:100%;
}
#content {
position:relative;
}
#content #text {
position:relative;
width:950px;
height:215px;
color:red;
}
</code></pre>
<p><a href="http://jsfiddle.net/uorgj4e1/" rel="noreferrer">http://jsfiddle.net/uorgj4e1/</a></p> |
35,127,086 | Android : inApp purchase receipt validation google play | <p>I am using google wallet for my payment gateway, after purchasing the product google giving me a below response that</p>
<pre><code>{
"orderId":"12999763169054705758.1371079406387615",
"packageName":"com.example.app",
"productId":"exampleSku",
"purchaseTime":1345678900000,
"purchaseState":0,
"developerPayload":"bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ",
"purchaseToken":"rojeslcdyyiapnqcynkjyyjh"
}
</code></pre>
<p>I am trying to make use of <strong>Receipt Validation</strong> that google play newly introduced.In Google Developer console I made <strong>certificate key</strong> by Service Account in the Permission. But I am confused how to make use of Receipt Validation after purchasing a Product from the Google Play-store.</p>
<p>So can anyone please help me how to do the <strong>Receipt validation</strong> of <code>InApp</code> Purchase.</p> | 35,138,885 | 5 | 4 | null | 2016-02-01 09:35:06.297 UTC | 78 | 2022-09-19 09:46:06.917 UTC | 2016-05-17 19:33:15.83 UTC | null | 881,229 | null | 5,571,630 | null | 1 | 109 | android|in-app-purchase|android-pay | 90,801 | <p>Google provides receipt validation through the <a href="https://developers.google.com/android-publisher/" rel="nofollow noreferrer">Google Play Developer API</a>, within the API are two endpoints you will be most interested in: <a href="https://developers.google.com/android-publisher/api-ref/purchases/products/get" rel="nofollow noreferrer">Purchases.products: get</a> and <a href="https://developers.google.com/android-publisher/api-ref/purchases/subscriptions/get" rel="nofollow noreferrer">Purchases.subscriptions: get</a>.</p>
<p><code>Purchases.products: get</code> can be used to verify a non-auto-renewing product purchase, where <code>Purchases.subscriptions: get</code> is for verifying and re-verifying auto-renewing product subscriptions.</p>
<p>To use either endpoint you must know the <code>packageName</code>, <code>productId</code>, <code>purchaseToken</code> all of these can be found in the payload you received on purchase. You also need an <code>access_token</code> which you can get by creating a Google API service account.</p>
<p>To get started with a service account first go to the Google play Developer console <a href="https://play.google.com/apps/publish/?dev_acc=04297363376525689732#ApiAccessPlace" rel="nofollow noreferrer">API access settings page</a> and click the Create new project button:</p>
<p><a href="https://i.stack.imgur.com/dR5yW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dR5yW.jpg" alt="Create a new Google API Project" /></a></p>
<p>You should now see a new Linked Project and a few new sections, in the the Service Account section, click the Create service account button.</p>
<p><a href="https://i.stack.imgur.com/pMZL7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pMZL7.jpg" alt="Create a new Service Account" /></a></p>
<p>You will be presented with an info box with instructions to create your service account. Click the link to Google Developers Console and a new tab will spawn.</p>
<p><a href="https://i.stack.imgur.com/eGNB4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eGNB4.jpg" alt="Open the Google Developers Console" /></a></p>
<p>Now click Create new Client ID, select Service account from the options and click Create Client ID.</p>
<p><a href="https://i.stack.imgur.com/Njl6M.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Njl6M.jpg" alt="Create a new Client ID" /></a></p>
<p>A JSON file will download, this is your JSON Web Token you will use to exchange for an <code>access_token</code> so keep it safe.</p>
<p>Next, switch tabs back to the Google play Developer console and click Done in the info box. You should see your new service account in the list. Click on Grant access next to the service account email.</p>
<p><a href="https://i.stack.imgur.com/7Jaij.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7Jaij.jpg" alt="Grant access" /></a></p>
<p>Next under the Choose a role for this user, select Finance and click Add user.</p>
<p><a href="https://i.stack.imgur.com/HdgEI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HdgEI.jpg" alt="Set the role to Finance" /></a></p>
<p>You have now set up your service account and it has all the necessary access to perform receipt validations. Next up is exchanging your JWT for an access_token.</p>
<p>The <code>access_token</code> expires after one hour of exchange you so need some server code to handle this and Google have provided several libraries in many languages to handle this (list not exhaustive):</p>
<ul>
<li>Ruby: <a href="https://github.com/google/google-api-ruby-client" rel="nofollow noreferrer">https://github.com/google/google-api-ruby-client</a></li>
<li>Node.js: <a href="https://github.com/google/google-api-nodejs-client" rel="nofollow noreferrer">https://github.com/google/google-api-nodejs-client</a></li>
<li>Java: <a href="https://github.com/google/google-api-java-client" rel="nofollow noreferrer">https://github.com/google/google-api-java-client</a></li>
<li>Python: <a href="https://github.com/google/google-api-python-client" rel="nofollow noreferrer">https://github.com/google/google-api-python-client</a></li>
<li>C#: <a href="https://github.com/googleapis/google-api-dotnet-client" rel="nofollow noreferrer">https://github.com/googleapis/google-api-dotnet-client</a></li>
</ul>
<p>I won't go into detail because there is plenty of documentation on how to use these libraries, but I will mention you want to use the <code>https://www.googleapis.com/auth/androidpublisher</code> as the OAuth2 scope, the <code>client_email</code> from the JWT as the <code>issuer</code> and the public key you can get from the <code>private_key</code> and the passphrase <code>notasecret</code> will be used for the <code>signing_key</code>.</p>
<p>Once you have the <code>access_token</code> you're good to go (at least for the next hour at which point you will want to request a new one following the same process in the above paragraph).</p>
<p>To check the status of a consumable (non-auto-renewing) purchase make a http <code>get</code> request to: <code>https://www.googleapis.com/androidpublisher/v2/applications/com.example.app/purchases/products/exampleSku/tokens/rojeslcdyyiapnqcynkjyyjh?access_token=your_access_token</code></p>
<p>If you get a 200 http response code, everything went as planed and your purchase was valid. A 404 will mean your token is invalid so the purchase was most likely a fraud attempt. A 401 will mean your access token is invalid and a 403 will mean your service account has insufficient access, check that you have enabled <strong>Finance</strong> for the access account in the Google Play Developer console.</p>
<p>The response from a 200 will look similar to this:</p>
<pre><code>{
"kind": "androidpublisher#productPurchase",
"purchaseTimeMillis": long,
"purchaseState": integer,
"consumptionState": integer,
"developerPayload": string
}
</code></pre>
<p>For an explanation of each property see <a href="https://developers.google.com/android-publisher/api-ref/purchases/products" rel="nofollow noreferrer">https://developers.google.com/android-publisher/api-ref/purchases/products</a>.</p>
<p>Subscriptions are similar however the endpoint looks like this:</p>
<p><code>https://www.googleapis.com/androidpublisher/v2/applications/packageName/purchases/subscriptions/subscriptionId/tokens/token?access_token=you_access_token</code></p>
<p>And the response should contain these properties:</p>
<pre><code>{
"kind": "androidpublisher#subscriptionPurchase",
"startTimeMillis": long,
"expiryTimeMillis": long,
"autoRenewing": boolean
}
</code></pre>
<p>See <a href="https://developers.google.com/android-publisher/api-ref/purchases/subscriptions" rel="nofollow noreferrer">https://developers.google.com/android-publisher/api-ref/purchases/subscriptions</a> for the property descriptions and note that <code>startTimeMillis</code> and <code>expiryTimeMillis</code> will be subject to change depending on the duration of the subscription.</p>
<p>Happy validating!</p> |
741,050 | Writing effective XSLT | <p><strong>What are the principles and patterns that go into writing effective XSLT?</strong></p>
<p>When I say "effective" I mean that it is</p>
<ol>
<li>Well-structured and readable</li>
<li>Simple, concise</li>
<li>Efficient (i.e. has good performance)</li>
</ol>
<p>In short, I'm looking for the best practices for XSLT.</p>
<p>I've already seen <a href="https://stackoverflow.com/questions/434976/how-do-i-profile-and-optimize-an-xslt">the question regarding efficiency</a>, but efficient code loses its value if you can't understand what it's doing. </p> | 753,451 | 5 | 0 | null | 2009-04-12 00:24:52.91 UTC | 16 | 2009-04-15 20:00:42.263 UTC | 2017-05-23 11:51:37.713 UTC | null | -1 | null | 81,098 | null | 1 | 14 | xml|xslt | 4,036 | <p>I think that a good way to answer this question would to approach it from the other side. What practices make XSLT <em>ineffective</em>, and why?</p>
<p>Some of the things that I've seen that result in ineffective XSLT:</p>
<ol>
<li><p><strong>Overuse of <code>for-each</code>.</strong> Everyone's said it; I'm saying it again. I find that <code>for-each</code> is often a sign of the developer trying to employ traditional programming techniques in a declarative language.</p></li>
<li><p><strong>Underutilizing XPath.</strong> A lot of bad XSLT I've seen exists purely because the developer didn't understand predicates, axis specifiers, <code>position()</code>, and <code>current()</code>, and so he implemented logic using XSLT constructs instead.</p></li>
<li><p><strong>Underutilizing metadata.</strong> You can sometimes eliminate an <em>enormous</em> amount of XSLT by providing your transform with metadata. </p></li>
<li><p><strong>Underutilizing pre-processing.</strong> If, for instance, an XML document contains data that has to be parsed using XSLT string manipulation, it's often much simpler to do all of the parsing outside of XSLT and either add the parsed results to the XML or pass the parsed results as an argument to the transform. I've seen some remarkably unmaintainable XSLT implementing business logic that would be trivial to implement in C# or Python. </p></li>
</ol>
<p>The biggest problem that I'm running into in my own XSLT world (I have several 3,000+ line transforms that I'm maintaining) is dead code. I'm certain that there are templates in my transforms that will never be used again, because the conditions they're testing for will never arise again. There's no way to determine programmatically if something like <code><xsl:template match="SomeField[contains(., "some value")]></code> is alive or dead, because it's contingent on something that metadata can't tell you.</p> |
564,319 | Achieving Thread-Safety | <p><strong>Question</strong> How can I make sure my application is thread-safe? Are their any common practices, testing methods, things to avoid, things to look for?</p>
<p><strong>Background</strong> I'm currently developing a server application that performs a number of background tasks in different threads and communicates with clients using Indy (using another bunch of automatically generated threads for the communication). Since the application should be highly availabe, a program crash is a very bad thing and I want to make sure that the application is thread-safe. No matter what, from time to time I discover a piece of code that throws an exception that never occured before and in most cases I realize that it is some kind of synchronization bug, where I forgot to synchronize my objects properly. Hence my question concerning best practices, testing of thread-safety and things like that.</p>
<p>mghie: Thanks for the answer! I should perhaps be a little bit more precise. Just to be clear, I know about the principles of multithreading, I use synchronization (monitors) throughout my program and I know how to differentiate threading problems from other implementation problems. But nevertheless, I keep forgetting to add proper synchronization from time to time. Just to give an example, I used the RTL sort function in my code. Looked something like</p>
<pre><code>FKeyList.Sort (CompareKeysFunc);
</code></pre>
<p>Turns out, that I had to synchronize FKeyList while sorting. It just don't came to my mind when initially writing that simple line of code. It's these thins I wanna talk about. What are the places where one easily forgets to add synchronization code? How do YOU make sure that you added sync code in all important places?</p> | 564,354 | 5 | 0 | null | 2009-02-19 07:46:23.513 UTC | 16 | 2010-06-07 14:30:57.837 UTC | 2009-02-19 08:13:28.317 UTC | Smasher | 62,391 | Smasher | 62,391 | null | 1 | 19 | multithreading|delphi|synchronization|thread-safety | 2,770 | <p>You can't really test for thread-safeness. All you can do is show that your code isn't thread-safe, but if you know how to do that you already know what to do in your program to fix that particular bug. It's the bugs you don't know that are the problem, and how would you write tests for those? Apart from that threading problems are much harder to find than other problems, as the act of debugging can already alter the behaviour of the program. Things will differ from one program run to the next, from one machine to the other. Number of CPUs and CPU cores, number and kind of programs running in parallel, exact order and timing of stuff happening in the program - all of this and much more will have influence on the program behaviour. [I actually wanted to add the phase of the moon and stuff like that to this list, but you get my meaning.]</p>
<p>My advice is to stop seeing this as an implementation problem, and start to look at this as a program design problem. You need to learn and read all that you can find about multi-threading, whether it is written for Delphi or not. In the end you need to understand the underlying principles and apply them properly in your programming. Primitives like critical sections, mutexes, conditions and threads are something the OS provides, and most languages only wrap them in their libraries (this ignores things like green threads as provided by for example Erlang, but it's a good point of view to start out from).</p>
<p>I'd say start with the <a href="http://en.wikipedia.org/wiki/Thread_(computer_science)" rel="noreferrer">Wikipedia article on threads</a> and work your way through the linked articles. I have started with the book <a href="http://www.oreilly.de/catalog/9781565922969/" rel="noreferrer">"Win32 Multithreaded Programming"</a> by Aaron Cohen and Mike Woodring - it is out of print, but maybe you can find something similar.</p>
<p><strong>Edit:</strong> Let me briefly follow up on your edited question. All access to data that is not read-only needs to be properly synchronized to be thread-safe, and sorting a list is not a read-only operation. So obviously one would need to add synchronization around all accesses to the list.</p>
<p>But with more and more cores in a system constant locking will limit the amount of work that can be done, so it is a good idea to look for a different way to design your program. One idea is to introduce as much read-only data as possible into your program - locking is no longer necessary, as all access is read-only.</p>
<p>I have found interfaces to be a very valuable aid in designing multi-threaded programs. Interfaces can be implemented to have only methods for read-only access to the internal data, and if you stick to them you can be quite sure that a lot of the potential programming errors do not occur. You can freely share them between threads, and the thread-safe reference counting will make sure that the implementing objects are properly freed when the last reference to them goes out of scope or is assigned another value.</p>
<p>What you do is create objects that descend from TInterfacedObject. They implement one or more interfaces which all provide only read-only access to the internals of the object, but they can also provide public methods that mutate the object state. When you create the object you keep both a variable of the object type and a interface pointer variable. That way lifetime management is easy, because the object will be deleted automatically when an exception occurs. You use the variable pointing to the object to call all methods necessary to properly set up the object. This mutates the internal state, but since this happens only in the active thread there is no potential for conflict. Once the object is properly set up you return the interface pointer to the calling code, and since there is no way to access the object afterwards except by going through the interface pointer you can be sure that only read-only access can be performed. By using this technique you can completely remove the locking inside of the object.</p>
<p>What if you need to change the state of the object? You don't, you create a new one by copying the data from the interface, and mutate the internal state of the new objects afterwards. Finally you return the reference pointer to the new object.</p>
<p>By using this you will only need locking where you get or set such interfaces. It can even be done without locking, by using the atomic interchange functions. See <a href="http://17slon.com/blogs/gabr/2009/02/hassle-free-critical-section.html" rel="noreferrer">this blog post</a> by Primoz Gabrijelcic for a similar use case where an interface pointer is set.</p> |
495,244 | How can I test a Windows DLL file to determine if it is 32 bit or 64 bit? | <p>I'd like to write a test script or program that asserts that all DLL files in a given directory are of a particular build type.</p>
<p>I would use this as a sanity check at the end of a build process on an SDK to make sure that the 64-bit version hasn't somehow got some 32-bit DLL files in it and vice versa.</p>
<p>Is there an easy way to look at a DLL file and determine its type?</p>
<p>The solution should work on both xp32 and xp64.</p> | 495,305 | 5 | 1 | null | 2009-01-30 11:42:31.553 UTC | 61 | 2021-11-09 10:54:54.007 UTC | 2017-01-06 23:09:10.053 UTC | null | 63,550 | morechilli | 5,427 | null | 1 | 278 | windows|dll|32bit-64bit | 291,961 | <h2>Gory details</h2>
<p>A DLL uses the PE executable format, and it's not too tricky to read that information out of the file.</p>
<p>See this <a href="http://reversingproject.info/wp-content/uploads/2009/05/an_in-depth_look_into_the_win32_portable_executable_file_format_part_1.pdf" rel="noreferrer">MSDN article on the PE File Format</a> for an overview. You need to read the MS-DOS header, then read the <a href="http://msdn.microsoft.com/en-us/library/ms680336(VS.85).aspx" rel="noreferrer">IMAGE_NT_HEADERS</a> structure. This contains the <a href="http://msdn.microsoft.com/en-us/library/ms680313(VS.85).aspx" rel="noreferrer">IMAGE_FILE_HEADER</a> structure which contains the info you need in the Machine member which contains one of the following values</p>
<ul>
<li>IMAGE_FILE_MACHINE_I386 (0x014c)</li>
<li>IMAGE_FILE_MACHINE_IA64 (0x0200)</li>
<li>IMAGE_FILE_MACHINE_AMD64 (0x8664)</li>
</ul>
<p>This information should be at a fixed offset in the file, but I'd still recommend traversing the file and checking the signature of the MS-DOS header and the IMAGE_NT_HEADERS to be sure you cope with any future changes. </p>
<h2>Use ImageHelp to read the headers...</h2>
<p>You can also use the <a href="http://msdn.microsoft.com/en-us/library/ms680321(VS.85).aspx" rel="noreferrer">ImageHelp API</a> to do this - load the DLL with <a href="http://msdn.microsoft.com/en-us/library/ms680209(VS.85).aspx" rel="noreferrer">LoadImage</a> and you'll get a <a href="http://msdn.microsoft.com/en-us/library/ms680349(VS.85).aspx" rel="noreferrer">LOADED_IMAGE</a> structure which will contain a pointer to an IMAGE_NT_HEADERS structure. Deallocate the LOADED_IMAGE with ImageUnload.</p>
<h2>...or adapt this rough Perl script</h2>
<p>Here's rough Perl script which gets the job done. It checks the file has a DOS header, then reads the PE offset from the IMAGE_DOS_HEADER 60 bytes into the file.</p>
<p>It then seeks to the start of the PE part, reads the signature and checks it, and then extracts the value we're interested in.</p>
<pre class="lang-perl prettyprint-override"><code>#!/usr/bin/perl
#
# usage: petype <exefile>
#
$exe = $ARGV[0];
open(EXE, $exe) or die "can't open $exe: $!";
binmode(EXE);
if (read(EXE, $doshdr, 64)) {
($magic,$skip,$offset)=unpack('a2a58l', $doshdr);
die("Not an executable") if ($magic ne 'MZ');
seek(EXE,$offset,SEEK_SET);
if (read(EXE, $pehdr, 6)){
($sig,$skip,$machine)=unpack('a2a2v', $pehdr);
die("No a PE Executable") if ($sig ne 'PE');
if ($machine == 0x014c){
print "i386\n";
}
elsif ($machine == 0x0200){
print "IA64\n";
}
elsif ($machine == 0x8664){
print "AMD64\n";
}
else{
printf("Unknown machine type 0x%lx\n", $machine);
}
}
}
close(EXE);
</code></pre> |
669,175 | Unit testing ASP.Net MVC Authorize attribute to verify redirect to login page | <p>This is probably going to turn out to be a case of just needing another pair of eyes. I must be missing something, but I cannot figure out why this kind of thing cannot be tested for. I'm basically trying to ensure that unauthenticated users cannot access the view by marking the controller with the [Authorize] attribute and I'm trying to tests this using the following code:</p>
<pre><code>[Fact]
public void ShouldRedirectToLoginForUnauthenticatedUsers()
{
var mockControllerContext = new Mock<ControllerContext>()
{ DefaultValue = DefaultValue.Mock };
var controller = new MyAdminController()
{ControllerContext = mockControllerContext.Object};
mockControllerContext.Setup(c =>
c.HttpContext.Request.IsAuthenticated).Returns(false);
var result = controller.Index();
Assert.IsAssignableFrom<RedirectResult>(result);
}
</code></pre>
<p>The RedirectResult I'm looking for is some kind of indication that the user is being redirected to the login form, but instead a ViewResult is always returned and when debugging I can see that the Index() method is successfully hit even though the user is not authenticated.</p>
<p>Am I doing something wrong? Testing at the wrong level? Should I rather be testing at the route level for this kind of thing?</p>
<p>I know that the [Authorize] attribute is working, because when I spin up the page, the login screen is indeed forced upon me - but how do I verify this in a test?</p>
<p>The controller and index method are very simple just so that I can verify the behaviour. I've included them for completeness:</p>
<pre><code>[Authorize]
public class MyAdminController : Controller
{
public ActionResult Index()
{
return View();
}
}
</code></pre>
<p>Any help appreciated...</p> | 670,838 | 5 | 1 | null | 2009-03-21 11:52:38.947 UTC | 30 | 2021-02-23 20:43:03.3 UTC | 2021-02-23 20:29:47.827 UTC | null | 3,850,405 | Rob G | 1,107 | null | 1 | 71 | c#|asp.net-mvc | 37,681 | <p>You are testing at the wrong level. The [Authorize] attribute ensures that the <em>routing</em> engine will never invoke that method for an unauthorized user - the RedirectResult will actually be coming from the route, not from your controller method.</p>
<p>Good news is - there's already test coverage for this (as part of the MVC framework source code), so I'd say you don't need to worry about it; just make sure your controller method does the right thing <em>when</em> it gets called, and trust the framework not to call it in the wrong circumstances.</p>
<p>EDIT: If you want to verify the presence of the attribute in your unit tests, you'll need to use reflection to inspect your controller methods as follows. This example will verify the presence of the Authorize attribute on the ChangePassword POST method in the 'New ASP.NET MVC 2 Project' demo that's installed with MVC2. </p>
<pre><code>[TestFixture]
public class AccountControllerTests {
[Test]
public void Verify_ChangePassword_Method_Is_Decorated_With_Authorize_Attribute() {
var controller = new AccountController();
var type = controller.GetType();
var methodInfo = type.GetMethod("ChangePassword", new Type[] { typeof(ChangePasswordModel) });
var attributes = methodInfo.GetCustomAttributes(typeof(AuthorizeAttribute), true);
Assert.IsTrue(attributes.Any(), "No AuthorizeAttribute found on ChangePassword(ChangePasswordModel model) method");
}
}
</code></pre> |
287,022 | Closing the browser should actually clear the session variables an ASP.net session id | <p>I have an ASP.net page. When I am closing the webpage I need to clear the session variables.</p>
<p>How to to handle this I need to maintain the timeout to 20 minutes.
If he closes and login for any number of times in the 20 minutes timed out time</p>
<p>Is there any possiblity for clearing the ASP.net session id</p> | 287,027 | 6 | 2 | null | 2008-11-13 14:15:12.517 UTC | 3 | 2013-11-18 11:45:28.457 UTC | 2008-11-13 15:22:32.693 UTC | DOK | 27,637 | balaweblog | 22,162 | null | 1 | 4 | asp.net|session | 40,459 | <p>[EDIT] As others have suggested, your session should time out eventually, but if you want to close the session before the timeout (for example to clean up large session objects) AND have javascript available to you...</p>
<p>You can do this with an <code>window.onbeforeunload</code> handler that posts back to a sign out page.</p>
<pre><code>function CloseSession( )
{
location.href = 'SignOut.aspx';
}
window.onbeforeunload = CloseSession;
</code></pre>
<p>You could also do it via AJAX. The SignOut.aspx page (or whatever platform you are using) should abandon the user's session.</p> |
21,384,040 | Why does the terminal show "^[[A" "^[[B" "^[[C" "^[[D" when pressing the arrow keys in Ubuntu? | <p>I've written a tiny program in Ansi C on Windows first, and I compiled it on Ubuntu with the built-in GCC now.</p>
<p>The program is simple:</p>
<ul>
<li>read the line from console with <code>scanf()</code>.</li>
<li>Analyze the string and calculate.</li>
</ul>
<p>But something weird happens. When I try to move the cursor, it prints four characters:</p>
<ul>
<li>pressing <kbd>Up</kbd> prints "<code>^[[A</code>"</li>
<li>pressing <kbd>Dn</kbd> prints "<code>^[[B</code>"</li>
<li>pressing <kbd>Rt</kbd> prints "<code>^[[C</code>"</li>
<li>pressing <kbd>Lt</kbd> prints "<code>^[[D</code>"</li>
</ul>
<p><img src="https://i.stack.imgur.com/kJOZP.png" alt=""></p>
<ul>
<li><p>How can this be avoided?</p></li>
<li><p>Why does it print these 4 characters instead of moving the cursor?</p></li>
</ul> | 21,384,212 | 6 | 4 | null | 2014-01-27 14:58:11.083 UTC | 28 | 2022-09-21 10:03:19.98 UTC | 2019-05-28 15:23:53.737 UTC | null | 16,287 | null | 2,998,612 | null | 1 | 107 | c|ubuntu | 108,440 | <p>Because that's what the keyboard actually sends to the PC (more precisely, what the terminal prints for what it actually receives from the keyboard). <code>bash</code> for example gets those values, deciphers them and understands that you want to move around, so it will either move the cursor (in case of left/right) or use its history to fetch previous commands (up/down). So you can't expect your program to magically support arrow keys.</p>
<p><strong>However</strong>, reading from standard input from the terminal already supports left/right arrow keys (I believe, but I'm not in Linux right now to test and make sure). So my guess is that there is another issue interfering. One possible cause could be that one of your modifier keys is stuck? Perhaps ALT, CTRL or SUPER?</p> |
46,832,072 | How to solve the circular dependency | <p>I have 3 services:</p>
<blockquote>
<p>auth.service.ts, account.service.ts, http.service.ts</p>
</blockquote>
<p>While user signup I should create new account therefore I imported account.service.ts to auth.service.ts. I should do it because I use signup form data for creating a new account.</p>
<pre><code>@Injectable()
export class AuthService {
constructor(public accountService: AccountService) {}
signUp(name: string, phone: string, email: string, password: string): void {
...
userPool.signUp(phone, password, attributeList, null, (err: any, result: any) => {
if (err) {
...
return;
}
this.accountService.createAccount(name, phone, email).subscribe(res => {
...
this.router.navigate(['/auth/confirmation-code']);
});
});
</code></pre>
<p>}</p>
<p>So as I use AWS Cognito I should add an authorization token from auth.service.ts to http.service.ts
therefore I imported auth.service.ts to http.service.ts.</p>
<pre><code>@Injectable()
export class HttpService {
private actionUrl: string;
private headers: Headers;
private options: RequestOptions;
constructor(
public _http: Http,
public authService: AuthService
) {
this.actionUrl = 'https://example.com/dev';
this.headers = new Headers();
this.authService.getAuthenticatedUser().getSession((err: any, session: any) => {
if(err) return;
this.headers.append('Authorization', session.getIdToken().getJwtToken());
});
this.headers.append('Content-Type', 'application/json');
this.headers.append('Accept', 'application/json');
this.headers.append('Access-Control-Allow-Headers', 'Content-Type, X-XSRF-TOKEN');
this.headers.append('Access-Control-Allow-Origin', '*');
this.options = new RequestOptions({ headers: this.headers });
}
get(request: string): Observable<any> {
return this._http.get(`${this.actionUrl}${request}`)
.map(res => this.extractData(res))
.catch(this.handleError);
}
</code></pre>
<p>In my account.service.ts I should use http.service.ts for creating new account.</p>
<pre><code>@Injectable()
export class AccountService {
constructor(public httpService: HttpService) {}
</code></pre>
<blockquote>
<p>WARNING in Circular dependency detected:
src/app/core/services/account.service.ts -> src/app/core/services/http.service.ts -> src/app/core/services/auth.service.ts -> src/app/core/services/account.service.ts</p>
<p>WARNING in Circular dependency detected:
src/app/core/services/auth.service.ts -> src/app/core/services/account.service.ts -> src/app/core/services/http.service.ts -> src/app/core/services/auth.service.ts</p>
<p>WARNING in Circular dependency detected:
src/app/core/services/http.service.ts -> src/app/core/services/auth.service.ts -> src/app/core/services/account.service.ts -> src/app/core/services/http.service.ts</p>
</blockquote>
<p>I understand that this is circular dependency Error.
How to solve it? Best practice?
All services fulfill their role and are important.</p> | 46,832,426 | 3 | 6 | null | 2017-10-19 14:16:57.103 UTC | 8 | 2021-04-01 07:14:55.597 UTC | 2017-10-21 16:42:50.49 UTC | null | 6,108,211 | null | 6,108,211 | null | 1 | 28 | angular | 42,705 | <p>You can use <code>Injector</code> for this. Inject it via constructor as usual, and then when you will need some service that leads to the circular dependency, get that service from it.</p>
<pre><code>class HttpService {
constructor(private injector: Injector) { }
doSomething() {
const auth = this.injector.get(AuthService);
// use auth as usual
}
}
</code></pre> |
54,571,009 | How to hide secret keys in Google Colaboratory from users having the sharing link? | <p>I written a script that extract some data from an API and build an Excel file. I'm not a dev, it is my first real program ever writted. I hosted the code on Google Colab.</p>
<p>There is API secret keys in clear. I want to share it with a Google Drive sharing link to people needing to generate the Excel file so that they can execute it. However I would prefer not to include API secret keys in clear in order to avoid accidental sharings outside of the entreprise. </p>
<p>I'm wondering how to hide this... Or how to provide users an alternative methode to execute the file without knowing the passwords. I don't have access to a shared webserver internally to the entreprise.</p>
<p>Regards</p>
<pre><code>CLIENT_KEY = u'*****'
CLIENT_SECRET = u'*****'
BASE_URL = u'*****'
access_token_key = '*****'
access_token_secret = '*****'
print ('Getting user profile...',)
oauth = OAuth(CLIENT_KEY, client_secret=CLIENT_SECRET, resource_owner_key=access_token_key,
resource_owner_secret=access_token_secret)
r = requests.get(url=BASE_URL + '1/user/me/profile', auth=oauth)
print (json.dumps(r.json(), sort_keys=True, indent=4, separators=(',', ': ')))
...
</code></pre> | 64,005,794 | 4 | 3 | null | 2019-02-07 10:15:55.78 UTC | 9 | 2021-09-23 23:36:38.323 UTC | null | null | null | null | 9,927,519 | null | 1 | 24 | python|security|google-colaboratory | 10,640 | <p>I would recommand using GCP's <strong><a href="https://cloud.google.com/secret-manager" rel="noreferrer">Secret Manager</a></strong> :</p>
<p>You get useful features such as rights management (in IAM & Admin), you can update your passwords via Secret versions, etc.. really useful.</p>
<p>Pre-requisits:</p>
<ul>
<li>Have a <strong>Google Cloud Platform</strong> project</li>
<li>In the <strong>IAM & Admin</strong>, you should have the role : "<strong>Secret Manager Secret Accessor</strong>"</li>
<li><strong><a href="https://console.cloud.google.com/security/secret-manager/" rel="noreferrer">Create a Secret</a></strong> in the Secret Manager :</li>
</ul>
<p>Here is a way to get your secret with python 3 :</p>
<pre><code># Install the module and import it :
!pip install google-cloud-secret-manager
from google.cloud import secretmanager
# Create a Client:
client = secretmanager.SecretManagerServiceClient()
secret_name = "my-secret" # => To be replaced with your secret name
project_id = 'my-project' # => To be replaced with your GCP Project
# Forge the path to the latest version of your secret with an F-string:
resource_name = f"projects/{project_id}/secrets/{secret_name}/versions/latest"
# Get your secret :
response = client.access_secret_version(request={"name": resource_name})
secret_string = response.payload.data.decode('UTF-8')
# Tada ! you secret is in the secret_string variable!
</code></pre>
<p>Do not try it with your real password or secret while testing this.</p>
<p>Enjoy !</p> |
1,771,741 | How to force sub classes to implement a method | <p>I am creating an object structure and I want all sub classes of the base to be forced to implement a method.</p>
<p>The only ways I could think of doing it were:</p>
<ol>
<li><p>An abstract class - Would work but the base class has some useful helper functions that get used by some of the sub classes.</p></li>
<li><p>An interface - If applied to just the base class then the sub classes don't have to implement the function only the base class does.</p></li>
</ol>
<p>Is this even possible?</p>
<p>N.B. This is a .NET 2 app.</p> | 1,771,754 | 5 | 2 | null | 2009-11-20 16:48:06.333 UTC | 5 | 2019-09-05 09:45:21.057 UTC | 2011-09-01 16:35:35.567 UTC | null | 8,707 | null | 41,709 | null | 1 | 53 | c#|oop|inheritance | 52,464 | <p>You can have abstract methods in a class with other methods that are implemented. The advantage over an interface is that you can include some code with your class and have the new object be forced to fill in the details for the abstract methods.</p>
<pre><code>public abstract class YourClass
{
// Your class implementation
public abstract void DoSomething(int x, int y);
public void DoSomethingElse(int a, string b)
{
// You can implement this here
}
}
</code></pre> |
2,283,034 | Python for a Perl programmer | <p>I am an experienced Perl developer with some degree of experience and/or familiarity with other languages (working experience with C/C++, school experience with Java and Scheme, and passing familiarity with many others).</p>
<p>I might need to get some web work done in Python (most immediately, related to Google App Engine). As such, I'd like to ask SO overmind for good references on how to best learn Python for someone who's coming from Perl background (e.g. the emphasis would be on differences between the two and how to translate perl idiomatics into Python idiomatics, as opposed to generic Python references). Something also centered on Web development is even better.
I'll take anything - articles, tutorials, books, sample apps?</p>
<p>Thanks!</p> | 2,283,300 | 7 | 1 | null | 2010-02-17 17:43:42.407 UTC | 49 | 2019-11-15 13:33:11.8 UTC | 2014-05-21 21:30:43.523 UTC | null | 2,963,652 | null | 119,280 | null | 1 | 57 | python|perl | 24,224 | <p>I've recently had to make a similar transition for work reasons, and it's been pretty painful. For better or worse, Python has a very different philosophy and way of working than Perl, and getting used to that can be frustrating. The things I've found most useful have been</p>
<ul>
<li>Spend a few hours going through all the basics. I found the <a href="http://docs.python.org/tutorial/" rel="noreferrer">official tutorial</a> quite good, if a little dry.</li>
<li>A good reference book to look up basic stuff ("how do I get the length of a string again?"). The ones I've found most useful are the <a href="https://rads.stackoverflow.com/amzn/click/com/0596158084" rel="noreferrer" rel="nofollow noreferrer">Python Pocket Reference</a> and <a href="https://rads.stackoverflow.com/amzn/click/com/0672329786" rel="noreferrer" rel="nofollow noreferrer">Python Essential Reference</a>.</li>
<li>Take a look at this handy <a href="http://wiki.python.org/moin/PerlPhrasebook" rel="noreferrer">Perl<->Python phrasebook</a> (common tasks, side by side, in both languages).</li>
<li>A reference for the Python approach to "common tasks". I use the <a href="http://oreilly.com/catalog/9780596001674" rel="noreferrer">Python Cookbook</a>.</li>
<li>An <a href="http://ipython.org/" rel="noreferrer">ipython</a> terminal open at all times to test syntax, introspect object methods etc.</li>
<li>Get <a href="http://pypi.python.org/pypi/pip" rel="noreferrer">pip</a> and <a href="http://pypi.python.org/pypi/setuptools" rel="noreferrer">easy-install</a> (to install Python modules easily).</li>
<li>Learn about unit tests fast. This is because without <code>use strict</code> you will feel crippled, and you will make many elementary mistakes which will appear as runtime errors. I recommend <a href="https://nose.readthedocs.org/en/latest/" rel="noreferrer">nose</a> rather than the <a href="http://docs.python.org/library/unittest.html" rel="noreferrer">unittest</a> framework that comes with the core install. unittest is very verbose if you're used to <a href="http://search.cpan.org/~mschwern/Test-Simple-0.94/lib/Test/More.pm" rel="noreferrer">Test::More</a>.</li>
<li>Check out Python questions on Stack Overflow. In particular, <a href="https://stackoverflow.com/questions/1011431/python-things-one-must-avoid/">Python - Things one MUST avoid</a> and <a href="https://stackoverflow.com/questions/530530/python-2-x-gotchas-and-landmines">Python 2.x gotchaβs and landmines</a> are well worth a read.</li>
</ul>
<p>Personally, I found <a href="http://www.diveintopython.net/toc/index.html" rel="noreferrer">Dive Into Python</a> annoying and patronising, but it's freely available online, so you can form your own judgment on that.</p> |
1,385,421 | Most elegant way to convert string array into a dictionary of strings | <p>Is there a built-in function for converting a string array into a dictionary of strings or do you need to do a loop here?</p> | 1,385,432 | 9 | 2 | null | 2009-09-06 11:18:06.24 UTC | 9 | 2022-09-09 08:04:17.093 UTC | 2016-07-09 06:28:45.503 UTC | null | 4,519,059 | null | 4,653 | null | 1 | 56 | c#|arrays|dictionary | 82,085 | <p>Assuming you're using .NET 3.5, you can turn any sequence (i.e. <code>IEnumerable<T></code>) into a dictionary:</p>
<pre><code>var dictionary = sequence.ToDictionary(item => item.Key,
item => item.Value)
</code></pre>
<p>where <code>Key</code> and <code>Value</code> are the appropriate properties you want to act as the key and value. You can specify just one projection which is used for the key, if the item itself is the value you want.</p>
<p>So for example, if you wanted to map the upper case version of each string to the original, you could use:</p>
<pre><code>var dictionary = strings.ToDictionary(x => x.ToUpper());
</code></pre>
<p>In your case, what do you want the keys and values to be?</p>
<p>If you actually just want a <em>set</em> (which you can check to see if it contains a particular string, for example), you can use:</p>
<pre><code>var words = new HashSet<string>(listOfStrings);
</code></pre> |
1,994,463 | How to cherry-pick a range of commits and merge them into another branch? | <p>I have the following repository layout:</p>
<ul>
<li>master branch (production)</li>
<li>integration</li>
<li>working</li>
</ul>
<p>What I want to achieve is to cherry-pick a range of commits from the working branch and merge it into the integration branch. I'm pretty new to git and I can't figure out how to exactly do this (the cherry-picking of commit ranges in one operation, not the merging) without messing the repository up. Any pointers or thoughts on this? Thanks!</p> | 1,994,491 | 10 | 0 | null | 2010-01-03 09:50:23.807 UTC | 266 | 2022-09-12 16:09:07.53 UTC | 2021-08-23 08:31:48.153 UTC | null | 16,678,905 | null | 131,404 | null | 1 | 807 | git|git-merge|git-cherry-pick | 457,676 | <p>When it comes to a range of commits, cherry-picking <del>is</del> <em>was</em> not practical.</p>
<p>As <a href="https://stackoverflow.com/a/3664543/6309">mentioned below</a> by <a href="https://stackoverflow.com/users/442025/keith-kim">Keith Kim</a>, Git 1.7.2+ introduced the ability to cherry-pick a range of commits (but you still need to be aware of the <a href="https://stackoverflow.com/questions/881092/how-to-merge-a-specific-commit-in-git/881112#881112">consequence of cherry-picking for future merge</a>)</p>
<blockquote>
<p>git cherry-pick" learned to pick a range of commits<br />
(e.g. "<code>cherry-pick A..B</code>" and "<code>cherry-pick --stdin</code>"), so did "<code>git revert</code>"; these do not support the nicer sequencing control "<code>rebase [-i]</code>" has, though.</p>
</blockquote>
<p><a href="https://stackoverflow.com/users/42961/damian">damian</a> <a href="https://stackoverflow.com/a/3933416/6309">comments</a> and warns us:</p>
<blockquote>
<p>In the "<code>cherry-pick A..B</code>" form, <strong><code>A</code> should be older than <code>B</code></strong>.<br />
<strong>If they're the wrong order the command will silently fail</strong>.</p>
</blockquote>
<p>If you want to pick the <strong>range <code>B</code> through <code>D</code> (including <code>B</code>)</strong> that would be <strong><code>B^..D</code></strong> (instead of <code>B..D</code>).<br />
See "<a href="https://stackoverflow.com/a/9853814/6309">Git create branch from range of previous commits?</a>" as an illustration.</p>
<p>As <a href="https://stackoverflow.com/users/2541573/jubobs">Jubobs</a> mentions <a href="https://stackoverflow.com/questions/1994463/how-to-cherry-pick-a-range-of-commits-and-merge-into-another-branch/1994491#comment51629396_1994491">in the comments</a>:</p>
<blockquote>
<p>This assumes that <code>B</code> is not a root commit; you'll get an "<code>unknown revision</code>" error otherwise.</p>
</blockquote>
<p>Note: as of Git 2.9.x/2.10 (Q3 2016), you can cherry-pick a range of commit directly on an orphan branch (empty head): see "<a href="https://stackoverflow.com/a/38285663/6309">How to make existing branch an orphan in git</a>".</p>
<hr />
<p>Original answer (January 2010)</p>
<p>A <code>rebase --onto</code> would be better, where you replay the given range of commit on top of your integration branch, as <a href="https://stackoverflow.com/questions/509859/what-is-the-best-way-to-git-patch-a-subrange-of-a-branch">Charles Bailey described here</a>.<br />
(also, look for "Here is how you would transplant a topic branch based on one branch to another" in the <a href="http://git-scm.com/docs/git-rebase" rel="noreferrer">git rebase man page</a>, to see a practical example of <code>git rebase --onto</code>)</p>
<p>If your current branch is integration:</p>
<pre class="lang-sh prettyprint-override"><code># Checkout a new temporary branch at the current location
git checkout -b tmp
# Move the integration branch to the head of the new patchset
git branch -f integration last_SHA-1_of_working_branch_range
# Rebase the patchset onto tmp, the old location of integration
git rebase --onto tmp first_SHA-1_of_working_branch_range~1 integration
</code></pre>
<p>That will replay everything between:</p>
<ul>
<li>after the parent of <code>first_SHA-1_of_working_branch_range</code> (hence the <code>~1</code>): the first commit you want to replay</li>
<li>up to "<code>integration</code>" (which points to the last commit you want to replay, from the <code>working</code> branch)</li>
</ul>
<p>to "<code>tmp</code>" (which points to where <code>integration</code> was pointing before)</p>
<p>If there is any conflict when one of those commits is replayed:</p>
<ul>
<li>either solve it and run "<code>git rebase --continue</code>".</li>
<li>or skip this patch, and instead run "<code>git rebase --skip</code>"</li>
<li>or cancel the all thing with a "<code>git rebase --abort</code>" (and put back the <code>integration</code> branch on the <code>tmp</code> branch)</li>
</ul>
<p>After that <code>rebase --onto</code>, <code>integration</code> will be back at the last commit of the integration branch (that is "<code>tmp</code>" branch + all the replayed commits)</p>
<p>With cherry-picking or <code>rebase --onto</code>, do not forget it has consequences on subsequent merges, as <a href="https://stackoverflow.com/questions/881092/how-to-merge-a-specific-commit-in-git/881112#881112">described here</a>.</p>
<hr />
<p>A pure "<code>cherry-pick</code>" solution is <a href="https://groups.google.com/d/msg/git-version-control/F0KYheOR2dY/pLj70x0A8L0J" rel="noreferrer">discussed here</a>, and would involve something like:</p>
<blockquote>
<p>If you want to use a patch approach then "git format-patch|git am" and "git cherry" are your options.<br />
Currently, <code>git cherry-pick</code> accepts only a single commit, but if you want to pick the range <code>B</code> through <code>D</code> that would be <code>B^..D</code> in git lingo, so</p>
</blockquote>
<pre class="lang-sh prettyprint-override"><code>git rev-list --reverse --topo-order B^..D | while read rev
do
git cherry-pick $rev || break
done
</code></pre>
<p>But anyway, when you need to "replay" a range of commits, the word "replay" should push you to use the "<code>rebase</code>" feature of Git.</p> |
1,449,276 | Multiline Text in a WPF Button | <p>How do I get multi-line text on a WPF Button using only C#? I have seen examples of using <code><LineBreak/></code> in XAML, but my buttons are created completely programmatically in C#. The number and labels on the buttons correspond to values in the domain model, so I don't think I can use XAML to specify this.</p>
<p>I have tried the naive approach below, but it does not work.</p>
<pre><code>Button b = new Button();
b.Content = "Two\nLines";
</code></pre>
<p>or</p>
<pre><code>b.Content = "Two\r\nLines";
</code></pre>
<p>In either case, all i see is the first line ("Two") of the text.</p> | 1,449,591 | 11 | 2 | null | 2009-09-19 19:17:22.88 UTC | 10 | 2021-06-02 03:35:24.817 UTC | 2017-08-22 15:40:59.147 UTC | null | 1,033,581 | null | 176,007 | null | 1 | 71 | c#|wpf|multiline | 99,785 | <p>Turns out the "\n" works fine. My grid had a fixed size, and there is simply no visual indication in a button that there's more text available (e.g., no "..." indicating a cutoff). Once I generously expanded the size of my grid, the button text showed up in two rows.</p> |
1,663,565 | List all devices, partitions and volumes in Powershell | <p>I have multiple volumes (as nearly everybody nowadays): on Windows they end up specified as C:, D: and so on. How do I list these all like on a Unix machine with "ls /mnt/" with Powershell? </p> | 1,663,623 | 11 | 1 | null | 2009-11-02 20:42:18.077 UTC | 16 | 2021-08-18 04:17:19.723 UTC | null | null | null | null | 59,300 | null | 1 | 72 | list|powershell|device | 216,667 | <p>To get all of the file system drives, you can use the following command:</p>
<pre><code>gdr -PSProvider 'FileSystem'
</code></pre>
<p><code>gdr</code> is an alias for <a href="http://technet.microsoft.com/en-us/library/hh849796.aspx" rel="noreferrer"><code>Get-PSDrive</code></a>, which includes all of the "virtual drives" for the registry, etc.</p> |
2,189,376 | How to change row color in datagridview | <p>I would like to change the color of a particular row in my datagridview. The row should be changed to red when the value of columncell 7 is less than the value in columncell 10. Any suggestions on how to accomplish this?</p> | 2,193,018 | 20 | 0 | null | 2010-02-03 03:00:12.233 UTC | 28 | 2022-07-15 20:26:09.517 UTC | 2022-07-02 14:36:08.327 UTC | null | 7,758,804 | null | 264,918 | null | 1 | 165 | c#|winforms|datagridview|background-color | 480,025 | <p>You need to loop through the rows in the datagridview and then compare values of columns 7 and 10 on each row.</p>
<p>Try this:</p>
<pre><code>foreach (DataGridViewRow row in vendorsDataGridView.Rows)
if (Convert.ToInt32(row.Cells[7].Value) < Convert.ToInt32(row.Cells[10].Value))
{
row.DefaultCellStyle.BackColor = Color.Red;
}
</code></pre> |
46,429,937 | IE11 - does a polyfill / script exist for CSS variables? | <p>I'm developing a webpage in a mixed web browser environment (Chrome/IE11).
IE11 doesn't support CSS variables, is there a polyfill or script that exists that would allow me to use CSS variables in IE11?</p> | 49,203,834 | 5 | 3 | null | 2017-09-26 15:02:30.873 UTC | 30 | 2020-09-09 09:34:41.843 UTC | null | null | null | null | 6,168,357 | null | 1 | 113 | css|internet-explorer-11|polyfills | 94,424 | <p>Yes, so long as you're processing root-level custom properties (IE9+).</p>
<ul>
<li><strong>GitHub</strong>: <a href="https://github.com/jhildenbiddle/css-vars-ponyfill" rel="noreferrer">https://github.com/jhildenbiddle/css-vars-ponyfill</a></li>
<li><strong>NPM</strong>: <a href="https://www.npmjs.com/package/css-vars-ponyfill" rel="noreferrer">https://www.npmjs.com/package/css-vars-ponyfill</a></li>
<li><strong>Demo</strong>: <a href="https://codepen.io/jhildenbiddle/pen/ZxYJrR" rel="noreferrer">https://codepen.io/jhildenbiddle/pen/ZxYJrR</a></li>
</ul>
<p>From the README:</p>
<blockquote>
<p><strong>Features</strong></p>
<ul>
<li>Client-side transformation of CSS custom properties to static values</li>
<li>Live updates of runtime values in both modern and legacy browsers</li>
<li>Transforms <code><link></code>, <code><style></code>, and <code>@import</code> CSS</li>
<li>Transforms relative <code>url()</code> paths to absolute URLs</li>
<li>Supports chained and nested <code>var()</code> functions</li>
<li>Supports <code>var()</code> function fallback values</li>
<li>Supports web components / shadow DOM CSS</li>
<li>Watch mode auto-updates on <code><link></code> and <code><style></code> changes</li>
<li>UMD and ES6 module available</li>
<li>TypeScript definitions included</li>
<li>Lightweight (6k min+gzip) and dependency-free</li>
</ul>
<p><strong>Limitations</strong></p>
<ul>
<li>Custom property support is limited to <code>:root</code> and <code>:host</code> declarations</li>
<li>The use of var() is limited to property values (per <a href="https://github.com/jhildenbiddle/css-vars-ponyfill" rel="noreferrer">W3C specification</a>)</li>
</ul>
</blockquote>
<p>Here are a few examples of what the library can handle:</p>
<p><strong>Root-level custom properties</strong></p>
<pre><code>:root {
--a: red;
}
p {
color: var(--a);
}
</code></pre>
<p><strong>Chained custom properties</strong></p>
<pre><code>:root {
--a: var(--b);
--b: var(--c);
--c: red;
}
p {
color: var(--a);
}
</code></pre>
<p><strong>Nested custom properties</strong></p>
<pre><code>:root {
--a: 1em;
--b: 2;
}
p {
font-size: calc(var(--a) * var(--b));
}
</code></pre>
<p><strong>Fallback values</strong></p>
<pre><code>p {
font-size: var(--a, 1rem);
color: var(--b, var(--c, var(--d, red)));
}
</code></pre>
<p><strong>Transforms <code><link></code>, <code><style></code>, and <code>@import</code> CSS</strong></p>
<pre><code><link rel="stylesheet" href="/absolute/path/to/style.css">
<link rel="stylesheet" href="../relative/path/to/style.css">
<style>
@import "/absolute/path/to/style.css";
@import "../relative/path/to/style.css";
</style>
</code></pre>
<p><strong>Transforms web components / shadow DOM</strong></p>
<pre><code><custom-element>
#shadow-root
<style>
.my-custom-element {
color: var(--test-color);
}
</style>
<div class="my-custom-element">Hello.</div>
</custom-element>
</code></pre>
<p>For the sake of completeness: <a href="https://www.w3.org/TR/css-variables/" rel="noreferrer">w3c specs</a></p>
<p>Hope this helps.</p>
<p>(Shameless self-promotion: Check)</p> |
18,182,170 | Overriding an automatic property | <p>since this</p>
<pre><code>public int MyInt{ get; set;}
</code></pre>
<p>is equivalent to</p>
<pre><code>private int _myInt;
public int MyInt{ get{return _myInt;} set{_myInt = value;} }
</code></pre>
<p>when you make the automatic property virtual</p>
<pre><code>public virtual int MyInt{ get; set;}
</code></pre>
<p>and then override this property in a child class</p>
<pre><code>public override int MyInt{ get{return someVar;} set{someVar = value;} }
</code></pre>
<p>does this child class now have an unwelcomed and hidden allocation of _myInt?</p> | 18,182,361 | 4 | 8 | null | 2013-08-12 08:09:01.18 UTC | 9 | 2013-08-12 11:20:50.533 UTC | null | null | null | null | 1,525,061 | null | 1 | 49 | c# | 5,500 | <p><strong><em>Short Answer</em></strong>: Yes, the <code>Child</code> allocates all <code>Base</code> class fields, so it still has the backing field allocated. However, you can't access it any other way than through <code>Base.MyInt</code> property.</p>
<p><strong><em>Long Answer</em></strong>:</p>
<p>Quick disassembly results.</p>
<p><code>Base</code> and <code>Child</code> classes implementation:</p>
<pre><code>public class Base
{
public virtual int MyInt { get; set; }
}
public class Child : Base
{
private int anotherInt;
public override int MyInt
{
get { return anotherInt; }
set { anotherInt = value; }
}
}
</code></pre>
<p><img src="https://i.stack.imgur.com/pitvd.png" alt="enter image description here"></p>
<p><strong>As you can see, the backing field exists within <code>Base</code> class.</strong> However, it is private, so you can't access it from <code>Child</code> class:</p>
<pre><code>.field private int32 '<MyInt>k__BackingField'
</code></pre>
<p>And your <code>Child.MyInt</code> property does not use that field. The property IL is:</p>
<pre><code>.method public hidebysig specialname virtual
instance int32 get_MyInt () cil managed
{
// Method begins at RVA 0x2109
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldfld int32 ConsoleApplication2.Child::anotherInt
IL_0006: ret
} // end of method Child::get_MyInt
.method public hidebysig specialname virtual
instance void set_MyInt (
int32 'value'
) cil managed
{
// Method begins at RVA 0x2111
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld int32 ConsoleApplication2.Child::anotherInt
IL_0007: ret
} // end of method Child::set_MyInt
</code></pre>
<p>Is uses <code>anotherInt</code> field, as you could expect.</p>
<p>The only ways to access the <code>'<MyInt>k__BackingField'</code> (indirectly, through <code>Base.MyInt</code> property) are:</p>
<ul>
<li><code>base.MyInt</code> from within <code>Child</code> class</li>
</ul> |
17,710,739 | Problems found loading Plugins in Android Studio | <p>After updating Gradle as suggested in this <a href="https://stackoverflow.com/a/16662045/932307">answer</a> the following error appears while using Android Studio 0.2.0</p>
<p><img src="https://i.stack.imgur.com/GzHR2.png" alt="enter image description here"></p>
<p>How to get over this one? </p> | 21,598,093 | 12 | 3 | null | 2013-07-17 21:37:43.98 UTC | 2 | 2020-10-12 15:20:01.457 UTC | 2017-05-23 10:31:11.217 UTC | null | -1 | null | 932,307 | null | 1 | 54 | android|gradle|android-studio | 44,989 | <p>go to <code>Settings-Plugins-IDE Settings</code> and just disable and enable again needed plugins - it helped me.
I think it was some bug on Studio</p> |
17,739,816 | How to open generated pdf using jspdf in new window | <p>I am using <strong>jspdf</strong> to generate a pdf file. Every thing is working fine. But how to open generated
pdf in new tab or new window.</p>
<p>I am using </p>
<pre><code>doc.output('datauri');
</code></pre>
<p>Which is opening the pdf in same tab.</p> | 26,090,019 | 15 | 0 | null | 2013-07-19 06:54:43.803 UTC | 18 | 2021-12-22 22:32:03.293 UTC | 2014-09-28 22:00:48.493 UTC | null | 1,391,249 | null | 1,297,813 | null | 1 | 54 | javascript|jspdf | 152,055 | <ol>
<li><p>Search in jspdf.js this:</p>
<pre><code>if(type == 'datauri') {
document.location.href ='data:application/pdf;base64,' + Base64.encode(buffer);
}
</code></pre></li>
<li><p>Add :</p>
<pre><code>if(type == 'datauriNew') {
window.open('data:application/pdf;base64,' + Base64.encode(buffer));
}
</code></pre></li>
<li>call this option 'datauriNew' Saludos ;)</li>
</ol> |
6,887,471 | How would I go about writing an interpreter in C? | <p>I'd love some references, or tips, possibly an e-book or two. I'm not looking to write a compiler, just looking for a tutorial I could follow along and modify as I go. Thank you for being understanding!</p>
<p>BTW: It must be C.</p>
<p>Any more replies would be appreciated.</p> | 6,888,074 | 3 | 7 | null | 2011-07-31 04:00:05.163 UTC | 27 | 2017-06-23 15:55:36.027 UTC | 2011-07-31 06:41:48.343 UTC | null | 569,183 | null | 569,183 | null | 1 | 22 | c|interpreter | 30,787 | <p>A great way to get started writing an interpreter is to write a simple machine simulator. Here's a simple language you can write an interpreter for:</p>
<p>The language has a stack and 6 instructions:</p>
<p><code>push <num></code> # push a number on to the stack</p>
<p><code>pop</code> # pop off the first number on the stack</p>
<p><code>add</code> # pop off the top 2 items on the stack and push their sum on to the stack. (remember you can add negative numbers, so you have subtraction covered too). You can also get multiplication my creating a loop using some of the other instructions with this one.</p>
<p><code>ifeq <address></code> # examine the top of the stack, if it's 0, continue, else, jump to <code><address></code> where <code><address></code> is a line number</p>
<p><code>jump <address></code> # jump to a line number</p>
<p><code>print</code> # print the value at the top of the stack</p>
<p><code>dup</code> # push a copy of what's at the top of the stack back onto the stack.</p>
<p>Once you've written a program that can take these instructions and execute them, you've essentially created a very simple stack based virtual machine. Since this is a very low level language, you won't need to understand what an AST is, how to parse a grammar into an AST, and translate it to machine code, etc. That's too complicated for a tutorial project. Start with this, and once you've created this little VM, you can start thinking about how you can translate some common constructs into this machine. e.g. you might want to think about how you might translate a C if/else statement or while loop into this language. </p>
<p>Edit:</p>
<p>From the comments below, it sounds like you need a bit more experience with C before you can tackle this task.</p>
<p>What I would suggest is to first learn about the following topics:</p>
<ul>
<li>scanf, printf, putchar, getchar - basic C IO functions </li>
<li>struct - the basic data structure in C </li>
<li>malloc - how to allocate memory, and the difference between stack memory and heap memory</li>
<li>linked lists - and how to implement a stack, then perhaps a binary tree (you'll need to
understand structs and malloc first)</li>
</ul>
<p>Then it'll be good to learn a bit more about the string.h library as well
- strcmp, strdup - a couple useful string functions that will be useful.</p>
<p>In short, C has a much higher learning curve compared to python, just because it's a lower level language and you have to manage your own memory, so it's good to learn a few basic things about C first before trying to write an interpreter, even if you already know how to write one in python.</p> |
6,361,858 | Django: Display current locale in a template | <p>I need to embed the current locale in a Django template's output (as part of a URL to be precise). I know that I can access the current <strong>language</strong> as <code>{{ LANGUAGE_CODE }}</code> if I <code>{ load i18n }</code> but is there a similar way to access the current <strong>locale</strong>?</p>
<p>I suppose I could use <code>to_locale()</code> in the view logic and put it in the context for the template, but I'm looking for something more generic that might be part of the Django framework itself. Is there such a syntax?</p> | 11,910,717 | 3 | 0 | null | 2011-06-15 17:38:12.41 UTC | 5 | 2014-06-17 16:21:43.2 UTC | null | null | null | null | 33,404 | null | 1 | 34 | django|localization|internationalization | 20,439 | <p>I solved this by including code below in the template </p>
<pre><code>{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}
</code></pre>
<p>and the variable <code>LANGUAGE_CODE</code> has the value you want (see also <a href="https://docs.djangoproject.com/en/dev/topics/i18n/translation/#switching-language-in-templates">django docs</a> for an example usage).</p> |
6,699,537 | How to use multiple configurations with logback in a single project? | <p>The configuration file for logback gets found on the classpath, and is therefore Eclipse-project-specific, which is not what I want. I'm using multiple Java utilities, all of them residing in a single project (this sharing the classpath), and I need to use a specific configuration for some of them.</p>
<p>I've tried variable substitution and Joram configurator, but nothing worked for me. This was most probably my fault, and I'm going to solve it one day, but for now I'd need a simple solution.</p> | 6,702,128 | 3 | 8 | null | 2011-07-14 20:30:34.123 UTC | 32 | 2020-03-13 16:16:14.433 UTC | null | null | null | null | 581,205 | null | 1 | 51 | java|logging|configuration|logback | 33,817 | <p>OPTION 1: specify the location of the logback configuration file with the logback.configurationFile system property. This does in fact allow you to have multiple configuration files per project. As per the <a href="https://logback.qos.ch/manual/configuration.html#configFileProperty" rel="noreferrer">logback documentation</a>, the value of the this property can be a URL, a resource on the class path or a path to a file external to the application. For example:<br/>
<code>-Dlogback.configurationFile=/path/to/config.xml</code></p>
<p>OPTION 2: use variable substitution to set the name of the log file with a system property. For example:</p>
<ol>
<li>Your appender can set the file as follows:<br/>
<code><file>/var/tmp/${mycompany.myapplication}.log</file></code></li>
<li>And then you can specify the value of that variable when launching java:<br/>
<code>-Dmycompany.myapplication=SomeUtility</code></li>
</ol>
<p>OPTION 3: set the logger level with a system property. This will allow you to log more/less. For example:</p>
<ol>
<li>Put this into your logback config file:<br/>
<code><logger name="com.mycompany" level="${mycompany.logging.level:-DEBUG}"/></code><br/>
This causes the specified package to log at DEBUG level by default.</li>
<li>If you want to change the logging level to INFO in a specific application, then pass the following to java when launching that application:<br/>
<code>-Dmycompany.logging.level=INFO</code></li>
</ol>
<p>OPTION 4: add/remove an appender by passing a system property command-line parameter to java. This will allow you to log to different places. Note that <a href="http://logback.qos.ch/setup.html#janino" rel="noreferrer">conditional processing requires janino</a>. For example:</p>
<ol>
<li>Put this into your logback config file wherever you would put an <code><appender-ref></code>, changing the <code>ref</code> value to one of your own <code><appender></code>s, of course:<br/>
<code>
<if condition="property("mycompany.logging.console").equalsIgnoreCase("true")">
<then><appender-ref ref="STDOUT"/></then></if>
</code></li>
<li>If you want to enable this appender, then pass the following to java when launching that application:<br/>
<code>-Dmycompany.logging.console=true</code></li>
</ol>
<p>Regarding system properties, you pass them to java as <code>-D</code> arguments, e.g.<br/>
<code>java -Dmy.property=/path/to/config.xml com.mycompany.MyMain</code></p> |
18,359,286 | How do I retrieve data from an Excel Workbook without opening in VBA? | <p>I have a folder, which is selectable by a user, which will contain 128 files. In my code, I open each document and copy the relevant data to my main workbook. All this is controlled through a userform. My problem is the time it takes to complete this process (about 50 seconds) - surely I can do it without opening the document at all?</p>
<p>This code is used to select the directory to search in:</p>
<pre><code>Private Sub CBSearch_Click()
Dim Count1 As Integer
ChDir "Directory"
ChDrive "C"
Count1 = 1
inputname = Application.GetOpenFilename("data files (*.P_1),*.P_1")
TBFolderPath.Text = CurDir()
End Sub
</code></pre>
<p>This Retrieves the files:</p>
<pre><code>Private Sub CBRetrieve_Click()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim i As Integer
Dim StrLen As Integer
Dim Folder As String
Dim A As String
Dim ColRef As Integer
Open_Data.Hide
StrLen = Len(TBFolderPath) + 1
Folder = Mid(TBFolderPath, StrLen - 10, 10)
For i = 1 To 128
A = Right("000" & i, 3)
If Dir(TBFolderPath + "\" + Folder + "-" + A + ".P_1") <> "" Then
Workbooks.OpenText Filename:= _
TBFolderPath + "\" + Folder + "-" + A + ".P_1" _
, Origin:=xlMSDOS, StartRow:=31, DataType:=xlDelimited, TextQualifier:= _
xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _
Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), _
Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1)), TrailingMinusNumbers:=True
Columns("B:B").Delete Shift:=xlToLeft
Rows("2:2").Delete Shift:=xlUp
Range(Range("A1:B1"), Range("A1:B1").End(xlDown)).Copy
Windows("Document.xls").Activate
ColRef = (2 * i) - 1
Cells(15, ColRef).Select
ActiveSheet.Paste
Windows(Folder + "-" + A + ".P_1").Activate
ActiveWindow.Close
End If
Next i
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
</code></pre>
<p>TBFolderPath is the contents of a textbox in the userform, and is the location of the files.</p>
<p>Sorry my code is so messy!</p>
<p>EDIT:
An example of the data is:</p>
<pre><code>TA2000 PLOT DATA FILE
FileName: c:\file
Version: 3.01
PlotNumber: 1
TotalPoints: 982
FrIndex: 460
F1Index: 427
F2Index: 498
FaIndex: 513
Transducer Type: 8024-004-A9
Serial Number:
Date: 09-Aug-2013
Operator: LSP
20-80kHz
Time: 10:51:35
Clf pF:
Range mS: 0.5
Aut/Man: Auto
Shunt pF:
Shunt uH:
Step size: 150 Hz
Rate: Max
Start: 1.0
Stop: 150.0
A---------B-------------C--------------D--------E
0---------0.003695---1.000078---0.2-----12
0---------0.004018---1.150238---0.2-----12
.
.
.
</code></pre>
<p>Where I am interested in A and C. Data has about 1000 entries.</p> | 18,359,984 | 2 | 6 | null | 2013-08-21 13:51:29.143 UTC | 1 | 2016-01-17 14:14:42.773 UTC | 2016-01-17 14:14:42.773 UTC | null | 4,370,109 | null | 2,575,586 | null | 1 | 3 | vba|excel | 39,043 | <p>I use something similar to this to cycle through Excel files in a folder and use ADODB to read the contents.</p>
<pre><code>Option Explicit
Private Sub ReadXL_ADODB()
Dim cnn1 As New ADODB.Connection
Dim rst1 As New ADODB.Recordset
Dim arrData() As Variant
Dim arrFields() As Variant
Dim EndofPath As String
Dim fs, f, f1, fc, s, filePath
Dim field As Long
Dim lngCount As Long
Dim filescount As Long
Dim wSheet As Worksheet
Dim lstRow As Long
Set wSheet = Sheet1 'Set sheet to import data to
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = True
.Show
For lngCount = 1 To .SelectedItems.Count
EndofPath = InStrRev(.SelectedItems(lngCount), "\")
filePath = Left(.SelectedItems(lngCount), EndofPath)
Next lngCount
End With
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFolder(filePath)
Set fc = f.Files
filescount = 0
For Each f1 In fc
DoEvents
'Open the connection to Excel then open the recordset
cnn1.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & CStr(f1) & ";" & _
"Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
'Imports from sheet named xDatabase and range A:EF
rst1.Open "SELECT * FROM [xDatabase$A:EF];", cnn1, adOpenStatic, adLockReadOnly
'If target fields are empty write field names
If WorksheetFunction.CountA(wSheet.Range("1:1")) = 0 Then
For field = 0 To rst1.Fields.Count - 1
wSheet.Range("A1").Offset(0, field).Value = rst1.Fields(field).Name
Next field
End If
arrData = rst1.GetRows
rst1.Close
cnn1.Close
Set rst1 = Nothing
Set cnn1 = Nothing
'Transpose array for writing to Excel
arrData = TransposeDim(arrData)
lstRow = LastRow(wSheet.Range("A:EF"))
wSheet.Range("A1").Offset(lstRow, 0).Resize(UBound(arrData, 1) + 1, UBound(arrData, 2) + 1).Value = arrData
filescount = filescount + 1
Application.StatusBar = "Imported file " & filescount & " of " & fc.Count
Next f1
Application.StatusBar = False
End Sub
Function TransposeDim(v As Variant) As Variant
' Custom Function to Transpose a 0-based array (v)
Dim X As Long, Y As Long, Xupper As Long, Yupper As Long
Dim tempArray As Variant
Xupper = UBound(v, 2)
Yupper = UBound(v, 1)
ReDim tempArray(Xupper, Yupper)
For X = 0 To Xupper
For Y = 0 To Yupper
tempArray(X, Y) = v(Y, X)
Next Y
Next X
TransposeDim = tempArray
End Function
Public Function LastRow(ByVal rng As Range) As Long
'The most accurate method to return last used row in a range.
On Error GoTo blankSheetError
'Identify next blank row
LastRow = rng.Find(What:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByRows).Row
'On Error GoTo 0 'not really needed
Exit Function
blankSheetError:
LastRow = 2 'Will produce error if blank sheet so default to row 2 as cannot have row 0
Resume Next
End Function
</code></pre> |
18,244,565 | How can I use executemany to insert into MySQL a list of dictionaries in Python | <p>I'm currently using MySQL and Python to scrape data from the web. Specifically, I am scraping table data and inserting it into my database. My current solution works, but I feel it is extremely inefficient and will most likely lock up my database if I don't rewrite the code. Here is what I currently use (partial code):</p>
<pre><code>itemBank = []
for row in rows:
itemBank.append((tempRow2,tempRow1,tempRow3,tempRow4)) #append data
#itemBank List of dictionaries representing data from each
row of the table. i.e.
('Item_Name':"Tomatoes",'Item_Price':"10",'Item_In_Stock':"10",'Item_Max':"30")
for item in itemBank:
tempDict1 = item[0]
tempDict2 = item[1]
tempDict3 = item[2]
tempDict4 = item[3]
q = """ INSERT IGNORE INTO
TABLE1
(
Item_Name,
Item_Price,
Item_In_Stock,
Item_Max,
Observation_Date
) VALUES (
"{0}",
"{1}",
"{2}",
"{3}",
"{4}"
)
""".format(tempDict1['Item_Name'],tempDict2['Item_Price'],tempDict3['Item_In_Stock'],
tempDict4['Item_Max'],getTimeExtra)
try:
x.execute(q)
conn.commit()
except:
conn.rollback()
</code></pre>
<p>Executing each row of the table is cumbersome. I've tried using <code>executemany</code>, but I can't seem to figure out how to access the values of the dictionaries correctly.
So, how can I use <code>executemany</code> here to insert into the database given the structure of my data?</p> | 18,245,311 | 2 | 1 | null | 2013-08-15 00:35:35.903 UTC | 5 | 2019-12-31 05:13:07.567 UTC | 2017-06-11 03:42:10.45 UTC | null | 6,263,942 | null | 2,134,413 | null | 1 | 32 | python|mysql|mysql-python | 72,086 | <pre><code>itemBank = []
for row in rows:
itemBank.append((
tempRow2['Item_Name'],
tempRow1['Item_Price'],
tempRow3['Item_In_Stock'],
tempRow4['Item_Max'],
getTimeExtra
)) #append data
q = """ insert ignore into TABLE1 (
Item_Name, Item_Price, Item_In_Stock, Item_Max, Observation_Date )
values (%s,%s,%s,%s,%s)
"""
try:
x.executemany(q, itemBank)
conn.commit()
except:
conn.rollback()
</code></pre>
<p>Hope it will help you</p> |
15,681,218 | What is the difference between structural Verilog and behavioural Verilog? | <p>As in the title, what are the main differences between structural and behavioural Verilog?</p> | 15,682,583 | 6 | 0 | null | 2013-03-28 11:59:40.287 UTC | 3 | 2020-09-15 05:50:45.503 UTC | null | null | null | null | 2,219,586 | null | 1 | 9 | verilog | 62,260 | <p>There is no strict definition of these terms, according to the IEEE Std. However, customarily, <strong>structural</strong> refers to describing a design using module instances (especially for the lower-level building blocks such as AND gates and flip-flops), whereas <strong>behavioral</strong> refers to describing a design using <code>always</code> blocks.</p>
<p>Gate netlists are always <strong>structural</strong>, and RTL code is typically <strong>behavioral</strong>. It is common for RTL to have instances of clock gates and synchronizer cells.</p> |
19,229,947 | java.util.concurrent.ExecutionException: java.lang.NullPointerException Error | <p>The following code snippet doesnt throw any error when executed in a standalone mode. When I deploy this into a web server [implementing a server's interface and added as JAR into classpath], I get </p>
<pre><code> java.util.concurrent.ExecutionException: java.lang.NullPointerException
at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at com.nbis.process.JSON_2_File_Split_V004.fn_1_parserEntity(JSON_2_File_Split_V004.java:256)
at com.nbis.process.JSON_2_File_Split_V004.fn_0_primaryCaller(JSON_2_File_Split_V004.java:177)
at com.nbis.process.JSON_2_File_Split_V004.execute(JSON_2_File_Split_V004.java:151)
</code></pre>
<p>Code Snippet:</p>
<pre><code>this.callable = new JSON_3_File_Process_V005(this.originalFileName, this.inProgressDirLoc, this.processedDirLoc, "[" + jSONRecord.toString() + "]", this.dataMDHolder, this.dataAccIDValueMap, this.dataCountryNameValueMap);
String[] fullContent = null;
try {
fullContent = executor.submit(this.callable).get();
} catch (ExecutionException e) {
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
log.info("Srii: " + errors.toString());
executor.shutdown();
return 7;
}
</code></pre>
<p>Adding the get's return value to an ExecutorCompletionService would be an option, but would that not kill the concept of asynchronous processing? In other words, I collect in StringBuilder the output string from callable get and store to a disk when the get count reaches a specific number. Once data is emitted to disk, I refresh the StringBuilder. This way I push data to a disk at regular intervals without having to keep them in memory.</p>
<p>Any suggestions as to what wrong am I doing here? Appreciate any inputs. Thank you.</p> | 19,242,929 | 2 | 2 | null | 2013-10-07 16:28:50.653 UTC | 1 | 2021-05-23 05:21:29.187 UTC | null | null | null | null | 1,818,593 | null | 1 | 6 | java|nullpointerexception|callable | 45,734 | <p>This is fixed. If it could useful:</p>
<p>The problem was with the way the variables were declared. I had to declare a class-level variable as static so the any changes applied to this one started reflecting everywhere else. Strangely enough, I dint see the problem when it was executed stand-alone.</p>
<pre><code>EDIT on 13112019: Moving my comment to the answer section, on request:
</code></pre>
<p>As its quite long time back, I dont recollect exactly the variable details. But I believe it is one of the following: this.originalFileName, this.inProgressDirLoc, this.processedDirLoc , this.dataMDHolder, this.dataAccIDValueMap, this.dataCountryNameValueMap I had to set them as static as values assigned [or modified] by any of the member was not reflecting during references of the variable within the class.</p> |
19,270,471 | Enter a new line and copy formula from cells above | <p>I am trying to create an Excel macro that does the following:</p>
<ol>
<li><p>Enter a new line at the end of document</p></li>
<li><p>copy the formulas from the cells above</p></li>
</ol>
<p>So far I have this:</p>
<pre><code> Sub New_Delta()
' Go to last cell
Range("A4").Select
Selection.End(xlDown).Select
LastCell = [A65536].End(xlUp).Offset(-1, 0).Address
Range(LastCell).Select
' Enter new line
Selection.EntireRow.Insert Shift:=xlUp, CopyOrigin:=xlFormatFromLeftOrAbove
' Copy formula from cell above
Dim oCell As Range
For Each oCell In Selection
If (oCell.Value = "") Then
oCell.Offset(-1, 0).Copy Destination:=oCell
End If
Next oCell
End Sub
</code></pre>
<p>This copies the formula for the first cell "A" but not the following ones</p>
<p>I want to do something like <code>Selection.Offset(0, 1).Select</code> and then iterate over that up to "K" (preferably without "G" and "H")</p>
<p>But I'm stuck, and could really use some help.</p>
<p>EDIT: I want something like this (Non working pseudo code)</p>
<pre><code> ' Copy formula from cell above
Dim oCell As Range
While (oCell.Offset(-1, 0).Value != "") ' If the cell above is not empty
oCell.Offset(-1, 0).Copy Destination:=oCell ' Copy the formula from the cell above
Selection.Offset(0, 1).Select ' Move one cell to the right
</code></pre> | 19,271,030 | 1 | 3 | null | 2013-10-09 11:12:47.537 UTC | null | 2018-06-18 12:17:21.32 UTC | 2015-09-11 04:07:56.29 UTC | null | 1,505,120 | null | 1,505,990 | null | 1 | 3 | excel|vba | 50,618 | <p>You could simply copy/insert the row before into the new row</p>
<pre><code>Sub New_Delta()
' Go to last cell
Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Select
' Copy formula from cell above
Rows(Selection.Row - 1).Copy
Rows(Selection.Row).Insert Shift:=xlDown
End Sub
</code></pre> |
40,994,719 | Cannot find name 'jquery' in angular2 | <p>I am working on to use the ng2-datetime. Installed through npm, but when I build the solution, I am getting an error that cannot find name 'jQuery'.</p>
<p>I have added the jQuery through npm and also tried to include the jquery library, but the issue still persists.
Can anyone tell what else to include? I'm using angular 2.2 with typescript and my IDE is VS2015</p>
<p><strong>app.module.ts</strong></p>
<p>just added the import statement</p>
<pre><code>import { NKDatetimeModule } from 'ng2-datetime/ng2-datetime';
</code></pre>
<p>and under imports </p>
<pre><code>@NgModule({
imports:[NKDatetimeModule ])}
</code></pre> | 40,995,659 | 6 | 6 | null | 2016-12-06 11:51:49.457 UTC | 14 | 2021-05-22 04:42:31.04 UTC | 2016-12-06 12:45:02.54 UTC | null | 1,449,157 | null | 3,510,028 | null | 1 | 24 | angular|typescript | 41,099 | <p>I got it working by installing <code>@types/jquery</code> from npm.</p> |
5,261,250 | An exception of type 'System.NullReferenceException' occurred in myproject.DLL but was not handled in user code | <p>What does this error mean?, I keep getting this error, it use to work fine and it just started throwing this error.... any help?</p>
<pre><code>img1.ImageUrl = ConfigurationManager.AppSettings.Get("Url").Replace("###", randomString)
+ Server.UrlEncode(((System.Web.UI.MobileControls.Form)Page.FindControl("mobileForm")).Title);
</code></pre>
<blockquote>
<p>An exception of type 'System.NullReferenceException' occurred in
MyProject.DLL but was not handled in user code</p>
<p>Additional information: Object reference not set to an instance of an
object.</p>
</blockquote> | 5,261,274 | 2 | 0 | null | 2011-03-10 14:39:35.83 UTC | 1 | 2018-07-07 15:47:42.663 UTC | 2018-07-07 15:47:42.663 UTC | null | 1,662,973 | null | 275,390 | null | 1 | 7 | c#|mobile-website | 114,320 | <p>It means somewhere in your chain of calls, you tried to access a Property or call a method on an object that was <code>null</code>.</p>
<p>Given your statement:</p>
<pre><code>img1.ImageUrl = ConfigurationManager
.AppSettings
.Get("Url")
.Replace("###", randomString)
+ Server.UrlEncode(
((System.Web.UI.MobileControls.Form)Page
.FindControl("mobileForm"))
.Title);
</code></pre>
<p>I'm guessing either the call to <code>AppSettings.Get("Url")</code> is returning null because the value isn't found or the call to <code>Page.FindControl("mobileForm")</code> is returning null because the control isn't found.</p>
<p>You could easily break this out into multiple statements to solve the problem:</p>
<pre><code>var configUrl = ConfigurationManager.AppSettings.Get("Url");
var mobileFormControl = Page.FindControl("mobileForm")
as System.Web.UI.MobileControls.Form;
if(configUrl != null && mobileFormControl != null)
{
img1.ImageUrl = configUrl.Replace("###", randomString) + mobileControl.Title;
}
</code></pre> |
4,976,897 | What is Address Family? | <p>When I read about socket programming, I get to know that AF_ stands for Address Family. But literally, a family should have many members. So, what are the members of, say, AF_INET address family?</p>
<p>In my opinion, I think it would be more appropriate to say Address <strong>Type</strong> than Addresss <strong>Family</strong>. Also this applies to PF (Protocol Family).</p>
<p>Thanks.</p> | 4,976,913 | 2 | 2 | null | 2011-02-12 07:21:38.123 UTC | 10 | 2022-05-09 06:22:54.123 UTC | 2011-02-12 07:27:11.463 UTC | null | 264,052 | null | 264,052 | null | 1 | 27 | sockets|network-programming | 33,056 | <p>Members of <code>AF_INET</code> address family are IPv4 addresses.</p>
<p>Members of <code>AF_INET6</code> address family are IPv6 addresses.</p>
<p>Members of <code>AF_UNIX</code> address family are names of Unix domain sockets (<code>/var/run/mysqld/mysqld.sock</code> is an example).</p>
<p>Members of <code>AF_IPX</code> address family are <a href="http://en.wikipedia.org/wiki/Internetwork_Packet_Exchange" rel="noreferrer">IPX</a> addresses, and so on. I don't think you really need to distinguish between <em>family</em> and <em>type</em> here. They are merely synonyms, except that <em>family</em> looks like more specialized, well-suited for this purpose, whilst <em>type</em> is a too much general word.</p> |
16,058,823 | how to make div center horizontally with fixed position? | <p>I want div to be center horizontally, css code is this:</p>
<pre><code><style type="text/css">
#footer{
position: fixed;
bottom: 20px;
background-color: red;
width:500px;
margin: auto;/*left:auto; right:auto;*/
}
</style>
</code></pre>
<p>and html code:</p>
<pre><code><body>
<div id="footer">hello world</div>
</body>
</code></pre>
<p>I think there is no need to explain my css code, it is almost self-explanatory, but the div is not center horizontally, is there any way to make this?
Thanks in advance.</p> | 16,058,913 | 4 | 1 | null | 2013-04-17 11:27:49.477 UTC | 3 | 2015-02-27 08:35:30.113 UTC | null | null | null | null | 1,626,906 | null | 1 | 9 | css|html|center | 48,523 | <p>Try this</p>
<pre><code>#footer{
position: fixed;
bottom: 20px;
background-color: red;
width:80%;
margin: 0 0 0 -40%;
left:50%;
}
</code></pre>
<p><a href="http://jsfiddle.net/7Q47W/">JS Fiddle Example</a></p>
<p>The point to be noted here is, the negative <code>margin-left</code> of exactly half value of <code>width</code> and set the <code>left</code> 50 % of the body </p> |
16,058,479 | How to create a new file in unix? | <p>How do I create a new file in a different directory? If the file exists it should also create a new file.</p>
<p>I am using the command:</p>
<pre><code>Touch workdirectory/filename.txt
</code></pre> | 16,058,856 | 2 | 5 | null | 2013-04-17 11:11:35.03 UTC | 1 | 2018-07-12 13:30:05.793 UTC | 2018-07-12 13:30:05.793 UTC | null | 6,656,269 | null | 2,285,422 | null | 1 | 11 | unix | 130,158 | <p>Try <code>> workdirectory/filename.txt</code></p>
<p>This would:</p>
<ul>
<li>truncate the file if it exists</li>
<li>create if it doesn't exist</li>
</ul>
<p>You can consider it equivalent to:</p>
<pre><code>rm -f workdirectory/filename.txt; touch workdirectory/filename.txt
</code></pre> |
322,467 | What CSS/JS/HTML/XML plugin(s) do you use in Eclipse? | <p>I'm looking for a good plugin for doing web front end work in Eclipse. I don't want something that completely takes over eclipse, or something that has masses of dependencies that need to be updated all the time, or something that is geared towards a particular server-side platform, or something that costs a heap.</p>
<p>Is there something light-weight out there that hits the sweet spot?</p>
<p>I tried aptana - found it took over my whole eclipse environment and put news feeds and other rubbish all over the place.</p>
<p>I then tried installing a subset of the aptana jar's and ended up pretty happy with the result.</p>
<p>Here's what I have in my plugins directory:</p>
<blockquote>
<p>com.aptana.ide.core_1.2.0.018852.jar
com.aptana.ide.snippets_1.2.0.018852.jar
com.aptana.ide.core.ui_1.2.0.018852.jar
com.aptana.ide.debug.core_1.2.0.018852.jar
com.aptana.ide.editor.css_1.2.0.018852.jar
com.aptana.ide.editor.html_1.2.0.018852.jar
com.aptana.ide.editor.js_1.2.0.018852.jar
com.aptana.ide.editors_1.2.0.018852.jar
com.aptana.ide.editors.codeassist_1.2.0.018852.jar
com.aptana.ide.epl_1.2.0.018852.jar
com.aptana.ide.io.file_1.2.0.018852.jar
com.aptana.ide.jface.text.source_1.2.0.018852.jar
com.aptana.ide.lexer_1.1.0.018852.jar
com.aptana.ide.libraries_1.2.0.18696
com.aptana.ide.libraries.jetty_1.2.0.018852
com.aptana.ide.logging_1.2.0.018852.jar
com.aptana.ide.parsing_1.2.0.018852.jar
com.aptana.ide.search.epl_1.2.0.018852.jar
com.aptana.ide.server_1.2.0.018852.jar
com.aptana.ide.server.core_1.2.0.018852.jar
com.aptana.ide.server.jetty_1.2.0.018852.jar
com.aptana.ide.server.ui_1.2.0.018852.jar</p>
</blockquote>
<p>..and in the features:</p>
<blockquote>
<p>com.aptana.ide.feature.editor.css_1.2.0.018852
com.aptana.ide.feature.editors_1.2.0.018852
com.aptana.ide.feature.editor.html_1.2.0.018852
com.aptana.ide.feature.editor.js_1.2.0.018852</p>
</blockquote> | 322,483 | 7 | 0 | null | 2008-11-26 23:01:38.86 UTC | 9 | 2018-07-16 21:03:50.977 UTC | 2011-06-09 12:19:50.75 UTC | null | 1,288 | Mark | 37,204 | null | 1 | 14 | javascript|html|css|eclipse | 28,364 | <p>Personally, I use the standalone community version of Aptana for that sort of thing, as I don't really use Eclipse for anything much else these days. </p>
<p>There is an Eclipse plugin version of Aptana, info available here: <a href="http://www.aptana.com/docs/index.php/Plugging_Aptana_into_an_existing_Eclipse_configuration" rel="nofollow noreferrer">http://www.aptana.com/docs/index.php/Plugging_Aptana_into_an_existing_Eclipse_configuration</a></p>
<p>Update: New link to get this plugin:
<a href="http://aptana.org/products/studio3/download" rel="nofollow noreferrer">http://aptana.org/products/studio3/download</a></p> |
312,936 | Windows Forms ProgressBar: Easiest way to start/stop marquee? | <p>I am using C# and Windows Forms. I have a normal progress bar working fine in the program, but now I have another operation where the duration cannot be easily calculated. I would like to display a progress bar but don't know the best way to start/stop the scrolling marquee. I was hoping for something as simple as setting the marquee speed and then having a start() and stop() but it doesn't appear to be that simple. Do I have to run an empty loop in the background? How do I best do this? Thanks</p> | 312,999 | 7 | 1 | null | 2008-11-23 20:49:07.07 UTC | 12 | 2017-01-20 15:03:56.88 UTC | null | null | null | kramed | 25,946 | null | 1 | 85 | c#|winforms|progress-bar | 230,837 | <p>Use a progress bar with the style set to <code>Marquee</code>. This represents an indeterminate progress bar.</p>
<pre><code>myProgressBar.Style = ProgressBarStyle.Marquee;
</code></pre>
<p>You can also use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.progressbar.marqueeanimationspeed.aspx" rel="noreferrer"><code>MarqueeAnimationSpeed</code></a> property to set how long it will take the little block of color to animate across your progress bar.</p> |
749,585 | Sorting in linear time? | <p>Given an input set of n integers in the range [0..n^3-1], provide a linear time sorting algorithm.</p>
<p>This is a review for my test on thursday, and I have no idea how to approach this problem.</p> | 749,593 | 8 | 6 | null | 2009-04-14 22:25:08.07 UTC | 7 | 2016-08-23 19:18:38.52 UTC | 2009-04-16 14:57:55.283 UTC | null | 1,527 | null | 78,182 | null | 1 | 24 | algorithm|sorting|complexity-theory|time-complexity | 75,302 | <p>Also take a look at related sorts too: <a href="http://en.wikipedia.org/wiki/Pigeonhole_sort" rel="noreferrer">pigeonhole sort</a> or <a href="http://en.wikipedia.org/wiki/Counting_sort" rel="noreferrer">counting sort</a>, as well as <a href="http://en.wikipedia.org/wiki/Radix_sort" rel="noreferrer">radix sort</a> as mentioned by Pukku.</p> |
303,761 | How do I get the path of the current drupal theme? | <p>The Drupal API has <a href="http://api.drupal.org/api/function/drupal_get_path/6" rel="noreferrer"><code>drupal_get_path($type, $name)</code></a> which will give the path of any particular theme or module. What if I want the path of the current theme?</p> | 306,380 | 8 | 1 | null | 2008-11-19 23:14:48.617 UTC | 6 | 2020-02-27 12:30:00.43 UTC | 2018-03-17 08:03:48.04 UTC | null | 225,647 | Steven Noble | 10,393 | null | 1 | 27 | drupal|drupal-6|drupal-theming | 55,143 | <p>Use the <a href="http://api.drupal.org/api/function/path_to_theme/6" rel="noreferrer"><code>path_to_theme</code></a> function.</p> |
1,162,352 | Converting XML to escaped text in XSLT | <p>How can I convert the following XML to an escaped text using XSLT?</p>
<p>Source:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<abc>
<def ghi="jkl">
mnop
</def>
</abc>
</code></pre>
<p>Output:</p>
<pre><code><TestElement>&lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;abc&gt;&lt;def ghi="jkl"&gt;
mnop
&lt;/def&gt;&lt;/abc&gt;</TestElement>
</code></pre>
<p>Currently, I'm trying the following XSLT and it doesn't seem to work properly:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="utf-8" />
<xsl:template match="/">
<xsl:variable name="testVar">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:variable>
<TestElement>
<xsl:value-of select="$testVar"/>
</TestElement>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>Output of XSLT statement by the .NET XslCompiledTransform comes out as the following:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?><TestElement>
mnop
</TestElement>
</code></pre> | 1,162,495 | 8 | 2 | null | 2009-07-21 23:49:57.81 UTC | 7 | 2014-07-03 06:49:04.053 UTC | 2009-07-22 00:02:56.55 UTC | null | 19,846 | null | 19,846 | null | 1 | 28 | xml|xslt | 42,185 | <p>Your code works the way it does because <code>xsl:value-of</code> retrieves the <a href="http://www.w3.org/TR/xpath#dt-string-value" rel="noreferrer">string-value</a> of the node set. </p>
<p>To do what you want, I'm afraid that you'll have to code it explicitly:</p>
<pre><code> <xsl:template match="/">
<TestElement>
<xsl:apply-templates mode="escape"/>
</TestElement>
</xsl:template>
<xsl:template match="*" mode="escape">
<!-- Begin opening tag -->
<xsl:text>&lt;</xsl:text>
<xsl:value-of select="name()"/>
<!-- Namespaces -->
<xsl:for-each select="namespace::*">
<xsl:text> xmlns</xsl:text>
<xsl:if test="name() != ''">
<xsl:text>:</xsl:text>
<xsl:value-of select="name()"/>
</xsl:if>
<xsl:text>='</xsl:text>
<xsl:call-template name="escape-xml">
<xsl:with-param name="text" select="."/>
</xsl:call-template>
<xsl:text>'</xsl:text>
</xsl:for-each>
<!-- Attributes -->
<xsl:for-each select="@*">
<xsl:text> </xsl:text>
<xsl:value-of select="name()"/>
<xsl:text>='</xsl:text>
<xsl:call-template name="escape-xml">
<xsl:with-param name="text" select="."/>
</xsl:call-template>
<xsl:text>'</xsl:text>
</xsl:for-each>
<!-- End opening tag -->
<xsl:text>&gt;</xsl:text>
<!-- Content (child elements, text nodes, and PIs) -->
<xsl:apply-templates select="node()" mode="escape" />
<!-- Closing tag -->
<xsl:text>&lt;/</xsl:text>
<xsl:value-of select="name()"/>
<xsl:text>&gt;</xsl:text>
</xsl:template>
<xsl:template match="text()" mode="escape">
<xsl:call-template name="escape-xml">
<xsl:with-param name="text" select="."/>
</xsl:call-template>
</xsl:template>
<xsl:template match="processing-instruction()" mode="escape">
<xsl:text>&lt;?</xsl:text>
<xsl:value-of select="name()"/>
<xsl:text> </xsl:text>
<xsl:call-template name="escape-xml">
<xsl:with-param name="text" select="."/>
</xsl:call-template>
<xsl:text>?&gt;</xsl:text>
</xsl:template>
<xsl:template name="escape-xml">
<xsl:param name="text"/>
<xsl:if test="$text != ''">
<xsl:variable name="head" select="substring($text, 1, 1)"/>
<xsl:variable name="tail" select="substring($text, 2)"/>
<xsl:choose>
<xsl:when test="$head = '&amp;'">&amp;amp;</xsl:when>
<xsl:when test="$head = '&lt;'">&amp;lt;</xsl:when>
<xsl:when test="$head = '&gt;'">&amp;gt;</xsl:when>
<xsl:when test="$head = '&quot;'">&amp;quot;</xsl:when>
<xsl:when test="$head = &quot;&apos;&quot;">&amp;apos;</xsl:when>
<xsl:otherwise><xsl:value-of select="$head"/></xsl:otherwise>
</xsl:choose>
<xsl:call-template name="escape-xml">
<xsl:with-param name="text" select="$tail"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
</code></pre>
<p>Note that this solution ignores comment nodes, and inserts unneccessary namespace nodes (as <code>namespace::</code> axis will include all nodes inherited from parent). Regarding namespaces, however, the resulting quoted XML will be semantically equivalent to the example that you provided in your reply (since those repeated redeclarations don't really change anything). </p>
<p>Also, this won't escape the <code><?xml ... ?></code> declaration, simply because it is not present in XPath 1.0 data model (it's not a processing instruction). If you actually need it in the output, you'll have to insert it manually (and make sure that encoding it specifies is consistent with serialization encoding of your XSLT processor).</p> |
1,267,902 | Generics - where T is a number? | <p>I'm trying to figure a way to create a generic class for number types only, for doing some calculations.</p>
<p>Is there a common interface for all number types (int, double, float...) that I'm missing???</p>
<p>If not, what will be the best way to create such a class?</p>
<p><strong>UPDATE:</strong></p>
<p>The main thing I'm trying to achieve is checking who is the bigger between two variables of type T.</p> | 1,268,404 | 8 | 4 | null | 2009-08-12 18:30:40.323 UTC | 14 | 2022-01-19 13:15:55.37 UTC | 2009-09-03 18:24:50.9 UTC | null | 139,300 | null | 139,300 | null | 1 | 73 | c#|generics|numbers | 97,131 | <p>What version of .NET are you using? If you are using .NET 3.5, then I have a <a href="https://jonskeet.uk/csharp/miscutil/usage/genericoperators.html" rel="noreferrer">generic operators implementation</a> in <a href="https://jonskeet.uk/csharp/miscutil/" rel="noreferrer">MiscUtil</a> (free etc).</p>
<p>This has methods like <code>T Add<T>(T x, T y)</code>, and other variants for arithmetic on different types (like <code>DateTime + TimeSpan</code>).</p>
<p>Additionally, this works for all the inbuilt, lifted and bespoke operators, and caches the delegate for performance.</p>
<p>Some additional background on why this is tricky is <a href="https://jonskeet.uk/csharp/genericoperators.html" rel="noreferrer">here</a>.</p>
<p>You may also want to know that <code>dynamic</code> (4.0) sort-of solves this issue indirectly too - i.e.</p>
<pre><code>dynamic x = ..., y = ...
dynamic result = x + y; // does what you expect
</code></pre>
<hr>
<p>Re the comment about <code><</code> / <code>></code> - you don't actually <em>need</em> operators for this; you just need:</p>
<pre><code>T x = ..., T y = ...
int c = Comparer<T>.Default.Compare(x,y);
if(c < 0) {
// x < y
} else if (c > 0) {
// x > y
}
</code></pre> |
315,078 | How do you handle multiple instances of setTimeout()? | <p>What is the most recommended/best way to stop multiple instances of a setTimeout function from being created (in javascript)?</p>
<p>An example (psuedo code):</p>
<pre><code>function mouseClick()
{
moveDiv("div_0001", mouseX, mouseY);
}
function moveDiv(objID, destX, destY)
{
//some code that moves the div closer to destination
...
...
...
setTimeout("moveDiv(objID, destX, destY)", 1000);
...
...
...
}
</code></pre>
<p>My issue is that if the user clicks the mouse multiple times, I have multiple instances of moveDiv() getting called.</p>
<p>The option I have seen is to create a flag, that only allows the timeout to be called if no other instance is available...is that the best way to go?</p>
<p>I hope that makes it clear....</p> | 315,133 | 9 | 0 | null | 2008-11-24 18:58:41.72 UTC | 11 | 2015-09-08 06:15:10.713 UTC | null | null | null | Markus | 2,490 | null | 1 | 24 | javascript | 52,094 | <p>when you call settimeout, it returns you a variable "handle" (a number, I think)</p>
<p>if you call settimeout a second time, you should first </p>
<pre><code>clearTimeout( handle )
</code></pre>
<p>then:</p>
<pre><code>handle = setTimeout( ... )
</code></pre>
<p>to help automate this, you might use a wrapper that associates timeout calls with a string (i.e. the div's id, or anything you want), so that if there's a previous settimeout with the same "string", it clears it for you automatically before setting it again, </p>
<p>You would use an array (i.e. dictionary/hashmap) to associate strings with handles.</p>
<pre><code>var timeout_handles = []
function set_time_out( id, code, time ) /// wrapper
{
if( id in timeout_handles )
{
clearTimeout( timeout_handles[id] )
}
timeout_handles[id] = setTimeout( code, time )
}
</code></pre>
<p>There are of course other ways to do this .. </p> |
787,895 | Reset the value of textarea after form submission | <ol>
<li>I want to send a message to userID=3 by going to /MyController/Message/3</li>
<li>This executes <code>Message()</code> [get] action, I enter some text in the text area and click on Save to post the form</li>
<li><code>Message()</code> [post] action saves the changes, resets the value of SomeText to empty string and returns to the view.</li>
</ol>
<p>At this point I expect the text area to be empty because I have set <code>ViewData["SomeText"]</code> to <code>string.Empty</code>.</p>
<p><strong>Why is text area value not updated to empty string after post action?</strong></p>
<p>Here are the actions:</p>
<pre><code>[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Message(int ID)
{
ViewData["ID"] = ID;
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Message(int ID, string SomeText)
{
// save Text to database
SaveToDB(ID, SomeText);
// set the value of SomeText to empty and return to view
ViewData["SomeText"] = string.Empty;
return View();
}
</code></pre>
<p>And the corresponding view:</p>
<pre><code><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm())
{ %>
<%= Html.Hidden("ID", ViewData["ID"])%>
<label for="SomeText">SomeText:</label>
<%= Html.TextArea("SomeText", ViewData["SomeText"]) %>
<input type="submit" value="Save" />
<% } %>
</asp:Content>
</code></pre> | 830,638 | 9 | 0 | null | 2009-04-25 00:05:32.35 UTC | 1 | 2020-10-15 06:28:16.83 UTC | 2020-10-15 06:28:16.83 UTC | null | 5,519,709 | null | 83,726 | null | 1 | 33 | c#|asp.net-mvc|forms | 39,023 | <p>The problem is the HtmlHelper is retrieving the ModelState value, which is filled with the posted data. Rather than hacking round this by resetting the ModelState, why not redirect back to the [get] action. The [post] action could also set a temporary status message like this:</p>
<pre><code>[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Message(int ID, string SomeText)
{
// save Text to database
SaveToDB(ID, SomeText);
TempData["message"] = "Message sent";
return RedirectToAction("Message");
}
</code></pre>
<p>This seems to me like more correct behaviour.</p> |
969,964 | When to use SOA (Service Oriented Architecture) | <p>I had a conversation with one of our architects recently and he summarized his use of SOA as "The only time we'll use services is when we need async actions otherwise we'll use go direct to the data store"</p>
<p>I thought about this statement and it seems fairly logical as services work well in a publish subscribe model, but I was wondering in what other scenarios you should be looking to use SOA?</p> | 970,000 | 10 | 0 | null | 2009-06-09 13:08:43.41 UTC | 15 | 2013-05-10 01:55:26.37 UTC | null | null | null | null | 493 | null | 1 | 16 | wcf|web-services|architecture|soap|soa | 17,330 | <p>We expose services to our customers because they shouldn't be able to connect to the datasource directly.</p>
<p>We expose services to ourselves because it's easier to spread them over different technologies using WCF. </p>
<p>We expose services because we have different user interfaces for the same datasource. And when we use services we save a third of the work.</p>
<p>It is never only because of the async actions.</p> |
61,150 | Mocking Static Blocks in Java | <p>My motto for Java is "just because Java has static blocks, it doesn't mean that you should be using them." Jokes aside, there are a lot of tricks in Java that make testing a nightmare. Two of the most I hate are Anonymous Classes and Static Blocks. We have a lot of legacy code that make use of Static Blocks and these are one of the annoying points in our push in writing unit tests. Our goal is to be able to write unit tests for classes that depend on this static initialization with minimal code changes. </p>
<p>So far my suggestion to my colleagues is to move the body of the static block into a private static method and call it <code>staticInit</code>. This method can then be called from within the static block. For unit testing another class that depends on this class could easily mock <code>staticInit</code> with <a href="https://jmockit.github.io/" rel="noreferrer">JMockit</a> to not do anything. Let's see this in example.</p>
<pre><code>public class ClassWithStaticInit {
static {
System.out.println("static initializer.");
}
}
</code></pre>
<p>Will be changed to</p>
<pre><code>public class ClassWithStaticInit {
static {
staticInit();
}
private static void staticInit() {
System.out.println("static initialized.");
}
}
</code></pre>
<p>So that we can do the following in a <a href="https://junit.org/junit5/" rel="noreferrer">JUnit</a>.</p>
<pre><code>public class DependentClassTest {
public static class MockClassWithStaticInit {
public static void staticInit() {
}
}
@BeforeClass
public static void setUpBeforeClass() {
Mockit.redefineMethods(ClassWithStaticInit.class, MockClassWithStaticInit.class);
}
}
</code></pre>
<p>However this solution also comes with its own problems. You can't run <code>DependentClassTest</code> and <code>ClassWithStaticInitTest</code> on the same JVM since you actually want the static block to run for <code>ClassWithStaticInitTest</code>.</p>
<p>What would be your way of accomplishing this task? Or any better, non-JMockit based solutions that you think would work cleaner?</p> | 61,215 | 10 | 1 | null | 2008-09-14 05:31:57.43 UTC | 16 | 2020-10-05 21:36:36.673 UTC | 2019-12-21 14:40:12.037 UTC | null | 9,361,512 | Cem Catikkas | 3,087 | null | 1 | 50 | java|unit-testing|mocking|jmockit|static-block | 52,176 | <p>When I run into this problem, I usually do the same thing you describe, except I make the static method protected so I can invoke it manually. On top of this, I make sure that the method can be invoked multiple times without problems (otherwise it is no better than the static initializer as far as the tests go).</p>
<p>This works reasonably well, and I can actually test that the static initializer method does what I expect/want it to do. Sometimes it is just easiest to have some static initialization code, and it just isn't worth it to build an overly complex system to replace it.</p>
<p>When I use this mechanism, I make sure to document that the protected method is only exposed for testing purposes, with the hopes that it won't be used by other developers. This of course may not be a viable solution, for example if the class' interface is externally visible (either as a sub-component of some kind for other teams, or as a public framework). It is a simple solution to the problem though, and doesn't require a third party library to set up (which I like).</p> |
1,283,388 | How to merge two tables overwriting the elements which are in both? | <p>I need to merge two tables, with the contents of the second overwriting contents in the first if a given item is in both. I looked but the standard libraries don't seem to offer this. Where can I get such a function?</p> | 1,283,399 | 10 | 2 | null | 2009-08-16 03:18:40.67 UTC | 16 | 2022-05-01 08:34:45.493 UTC | 2021-08-18 14:27:00.447 UTC | null | 4,694,621 | null | 117,069 | null | 1 | 80 | merge|lua|lua-table | 81,885 | <pre><code>for k,v in pairs(second_table) do first_table[k] = v end
</code></pre> |
1,267,869 | How can I force division to be floating point? Division keeps rounding down to 0? | <p>I have two integer values <code>a</code> and <code>b</code>, but I need their ratio in floating point. I know that <code>a < b</code> and I want to calculate <code>a / b</code>, so if I use integer division I'll always get 0 with a remainder of <code>a</code>.</p>
<p>How can I force <code>c</code> to be a floating point number in Python 2 in the following?</p>
<pre><code>c = a / b
</code></pre> | 1,267,892 | 11 | 0 | null | 2009-08-12 18:25:15.513 UTC | 129 | 2022-01-30 01:24:59.587 UTC | 2022-01-30 01:24:59.587 UTC | null | 63,550 | null | 1,084 | null | 1 | 776 | python|floating-point|integer|division|python-2.x | 742,083 | <p>In Python 2, division of two ints produces an int. In Python 3, it produces a float. We can get the new behaviour by importing from <code>__future__</code>.</p>
<pre><code>>>> from __future__ import division
>>> a = 4
>>> b = 6
>>> c = a / b
>>> c
0.66666666666666663
</code></pre> |
1,167,885 | Update SQL with consecutive numbering | <p>I want to update a table with consecutive numbering starting with 1. The update has a where clause so only results that meet the clause will be renumbered. Can I accomplish this efficiently without using a temp table?</p> | 1,167,926 | 11 | 4 | null | 2009-07-22 20:03:46.283 UTC | 12 | 2022-07-11 17:48:52.35 UTC | 2012-05-04 12:05:12.337 UTC | null | 619,960 | null | 55,124 | null | 1 | 50 | sql-server|tsql | 89,017 | <p>This probably depends on your database, but here is a solution for MySQL 5 that involves using a variable:</p>
<pre><code>SET @a:=0;
UPDATE table SET field=@a:=@a+1 WHERE whatever='whatever' ORDER BY field2,field3
</code></pre>
<p>You should probably edit your question and indicate which database you're using however.</p>
<p>Edit: I found a <a href="http://www.sqlmag.com/Article/ArticleID/93349/sql_server_93349.html" rel="noreferrer">solution</a> utilizing T-SQL for SQL Server. It's very similar to the MySQL method:</p>
<pre><code>DECLARE @myVar int
SET @myVar = 0
UPDATE
myTable
SET
@myvar = myField = @myVar + 1
</code></pre> |
528,303 | What are common reasons for deadlocks? | <p>Deadlocks are hard to find and very uncomfortable to remove.</p>
<p>How can I find error sources for deadlocks in my code? Are there any "deadlock patterns"?</p>
<p>In my special case, it deals with databases, but this question is open for every deadlock.</p> | 528,336 | 12 | 3 | null | 2009-02-09 14:20:45.917 UTC | 15 | 2015-11-09 13:47:36.163 UTC | 2009-06-29 09:52:02.89 UTC | Mitch Wheat | 16,076 | guerda | 32,043 | null | 1 | 40 | deadlock | 32,581 | <p>Update: This recent MSDN article, <a href="http://msdn.microsoft.com/en-us/magazine/cc546569.aspx" rel="noreferrer">Tools And Techniques to Identify Concurrency Issues</a>, might also be of interest</p>
<hr>
<p>Stephen Toub in the MSDN article <a href="http://msdn.microsoft.com/en-us/magazine/cc163352.aspx" rel="noreferrer">Deadlock monitor</a> states the following four conditions necessary for deadlocks to occur:</p>
<ul>
<li><p>A limited number of a particular resource. In the case of a monitor in C# (what you use when you employ the lock keyword), this limited number is one, since a monitor is a mutual-exclusion lock (meaning only one thread can own a monitor at a time). </p></li>
<li><p>The ability to hold one resource and request another. In C#, this is akin to locking on one object and then locking on another before releasing the first lock, for example: </p></li>
</ul>
<p><br></p>
<pre><code>lock(a)
{
...
lock(b)
{
...
}
}
</code></pre>
<ul>
<li><p>No preemption capability. In C#, this means that one thread can't force another thread to release a lock. </p></li>
<li><p>A circular wait condition. This means that there is a cycle of threads, each of which is waiting for the next to release a resource before it can continue.</p></li>
</ul>
<p>He goes on to explain that the way to avoid deadlocks is to avoid (or thwart) condition four.</p>
<blockquote>
<p><a href="http://msdn.microsoft.com/msdnmag/issues/06/04/Deadlocks" rel="noreferrer">Joe Duffy discusses several techniques</a>
for avoiding and detecting deadlocks,
including one known as lock leveling.
In lock leveling, locks are assigned
numerical values, and threads must
only acquire locks that have higher
numbers than locks they have already
acquired. This prevents the
possibility of a cycle. It's also
frequently difficult to do well in a
typical software application today,
and a failure to follow lock leveling
on every lock acquisition invites
deadlock.</p>
</blockquote> |
591,094 | How do you reindex an array in PHP but with indexes starting from 1? | <p>I have the following array, which I would like to reindex so the keys are reversed (ideally starting at 1):</p>
<p>Current array (<strong>edit:</strong> the array actually looks like this):</p>
<pre><code>Array (
[2] => Object
(
[title] => Section
[linked] => 1
)
[1] => Object
(
[title] => Sub-Section
[linked] => 1
)
[0] => Object
(
[title] => Sub-Sub-Section
[linked] =>
)
)
</code></pre>
<p>How it should be:</p>
<pre><code>Array (
[1] => Object
(
[title] => Section
[linked] => 1
)
[2] => Object
(
[title] => Sub-Section
[linked] => 1
)
[3] => Object
(
[title] => Sub-Sub-Section
[linked] =>
)
)
</code></pre> | 591,224 | 12 | 4 | null | 2009-02-26 15:46:37.157 UTC | 44 | 2022-08-02 22:03:38.157 UTC | 2020-10-04 22:27:03.273 UTC | htxt | 2,943,403 | htxt | 4,196 | null | 1 | 174 | php|arrays|indexing | 241,073 | <p>If you want to re-index starting to zero, simply do the following:</p>
<pre><code>$iZero = array_values($arr);
</code></pre>
<p>If you need it to start at one, then use the following:</p>
<pre><code>$iOne = array_combine(range(1, count($arr)), array_values($arr));
</code></pre>
<p>Here are the manual pages for the functions used:</p>
<ul>
<li><a href="http://ca3.php.net/manual/en/function.array-values.php" rel="noreferrer"><code>array_values()</code></a></li>
<li><a href="http://ca3.php.net/manual/en/function.array-combine.php" rel="noreferrer"><code>array_combine()</code></a></li>
<li><a href="http://ca3.php.net/manual/en/function.range.php" rel="noreferrer"><code>range()</code></a></li>
</ul> |
1,140,958 | What's a quick one-liner to remove empty lines from a python string? | <p>I have some code in a python string that contains extraneous empty lines. I would like to remove all empty lines from the string. What's the most pythonic way to do this?</p>
<p>Note: I'm not looking for a general code re-formatter, just a quick one or two-liner. </p>
<p>Thanks!</p> | 1,140,966 | 13 | 2 | null | 2009-07-17 00:21:12.437 UTC | 20 | 2021-06-15 20:45:51.603 UTC | null | null | null | null | 139,802 | null | 1 | 81 | python|string|line-endings | 93,967 | <p>How about:</p>
<pre><code>text = os.linesep.join([s for s in text.splitlines() if s])
</code></pre>
<p>where <code>text</code> is the string with the possible extraneous lines?</p> |
1,247,486 | List comprehension vs map | <p>Is there a reason to prefer using <code>map()</code> over list comprehension or vice versa? Is either of them generally more efficient or considered generally more pythonic than the other?</p> | 1,247,490 | 14 | 3 | null | 2009-08-07 23:43:31.943 UTC | 336 | 2022-03-22 07:42:21.363 UTC | 2018-11-18 18:56:37.47 UTC | null | 6,862,601 | null | 43,818 | null | 1 | 896 | python|list-comprehension|map-function | 293,466 | <p><code>map</code> may be microscopically faster in some cases (when you're NOT making a lambda for the purpose, but using the same function in map and a listcomp). List comprehensions may be faster in other cases and most (not all) pythonistas consider them more direct and clearer.</p>
<p>An example of the tiny speed advantage of map when using exactly the same function:</p>
<pre><code>$ python -m timeit -s'xs=range(10)' 'map(hex, xs)'
100000 loops, best of 3: 4.86 usec per loop
$ python -m timeit -s'xs=range(10)' '[hex(x) for x in xs]'
100000 loops, best of 3: 5.58 usec per loop
</code></pre>
<p>An example of how performance comparison gets completely reversed when map needs a lambda:</p>
<pre><code>$ python -m timeit -s'xs=range(10)' 'map(lambda x: x+2, xs)'
100000 loops, best of 3: 4.24 usec per loop
$ python -m timeit -s'xs=range(10)' '[x+2 for x in xs]'
100000 loops, best of 3: 2.32 usec per loop
</code></pre> |
15,816 | Changing the resolution of a VNC session in linux | <p>I use VNC to connect to a Linux workstation at work. At work I have a 20" monitor that runs at 1600x1200, while at home I use my laptop with its resolution of 1440x900.
If I set the vncserver to run at 1440x900 I miss out on a lot of space on my monitor, whereas if I set it to run at 1600x1200 it doesn't fit on the laptop's screen, and I have to scroll it all the time.</p>
<p>Is there any good way to resize a VNC session on the fly?</p>
<p>My VNC server is RealVNC E4.x (I don't remember the exact version) running on SuSE64.</p> | 1,083,668 | 15 | 3 | null | 2008-08-19 06:56:39.44 UTC | 91 | 2021-02-11 21:42:17.537 UTC | null | null | null | Nathan Fellman | 1,084 | null | 1 | 169 | linux|vnc | 549,285 | <p>Real VNC server 4.4 includes support for Xrandr, which allows resizing the VNC. Start the server with:</p>
<pre><code>vncserver -geometry 1600x1200 -randr 1600x1200,1440x900,1024x768
</code></pre>
<p>Then resize with:</p>
<pre><code>xrandr -s 1600x1200
xrandr -s 1440x900
xrandr -s 1024x768
</code></pre> |
797,596 | What are common pitfalls for startups driven by software developers? | <p>Myself and a friend have created a startup, but we are both software developers. We are quickly realizing that we are going to have to deal with and understand, all of the intricacies of business.</p>
<p>Are there any resources that can help us avoid common problems encountered by the non-business-savvy? How do you balance creating your product with maintaining realistic goals to reduce time-to-market.</p>
<p>It's like you need to take off your programmer hat and put on the business hat, and vice versa.</p> | 798,427 | 16 | 2 | null | 2009-04-28 12:21:51.807 UTC | 57 | 2013-11-27 14:51:15.163 UTC | 2013-11-27 14:51:15.163 UTC | user1228 | null | null | 62,195 | null | 1 | 44 | startup | 3,030 | <p>My software business was in a very, very small niche market centered on computer aided design of the magnetic layer in hard disk drives (www.micromagnetica.com - please note that I am in the process of closing down my business as the number of potential customers has shrunk to the point of making the business not viable. The web site reflects this point). I have been in business for 10 years and have done pretty well. My competition was a series of commercial and open source programs (mostly university or government sponsored), so, although the market was small, I was able to create a unique product that sold well.</p>
<p>Pitfalls:</p>
<ol>
<li><p><strong>Putting your needs above the customer</strong> - Customer comes first - always listen to your customer's needs and make sure your development follows their needs rather than yours. Every programmer has a list of things they want to learn or do. Don't use this list a guide for your development unless it solves an issue or helps create functionality that the customer wants/needs. This one point can make or break your company.</p></li>
<li><p><strong>Not clarifying your business idea</strong> - Put together a business plan - it will help clarify what you are doing. Read the book, <a href="https://rads.stackoverflow.com/amzn/click/com/1591840562" rel="noreferrer" rel="nofollow noreferrer">"The Art of the Start", by Guy Kawasaki</a> to get the business perspective of starting a business. If you need money then you can use this to help secure financing from either angel investors or venture capitalists. Otherwise, it will help clarify what you are doing.</p></li>
<li><p><strong>Not marketing yourself</strong> - Do this the following:</p>
<ul>
<li><p>(a) Find a good name for your company and secure your domain name. Even though a bad choice for company name won't kill you (my first company was called "Euxine Technologies" and it doesn't get much worse than that), but my product sold itself and was not encumbered by the name.</p></li>
<li><p>(b) Put together a web site as soon as possible with a good description of your product. Google will eventually find you and traffic will start flowing to your site.</p></li>
<li><p>(c) As soon as you have a working prototype create a mechanism where potential enthusiastic customers can download it and start helping you find bugs. You can make this the full version with a limited time or a limited version with no time limit. I have done both and both work. Make sure that users know it is a beta (or alpha) version of the software. The most important part of creating the beta user relationship is they will ask for features that you did not think about and this could take development along an otherwise unforeseen (and lucrative) path. This will also give you a way to keep your hand on the pulse of potential users. </p></li>
<li><p>(d) If your product is applicable to a particular industry go to relevant conferences<br>
(either get a booth or make contact with potential customers) and sell your product through demonstrations, flyers, and the distribution of free limited versions of your software on CD.</p></li>
</ul></li>
<li><p><strong>Not Branding yourself</strong> - come up with a logo that you will use to identify you and your product. This logo will show up on your web, your business stationary, and business cards.</p></li>
<li><p><strong>Not Managing your money</strong> - initially there is going to be a long spell before the money starts coming in. Be very frugal with your seed money. The money will not start coming in the moment your deem the software is ready to sell. There could be a time-lag of at least a couple of months between when people show interest in your software and when the sale comes in. This will depend on how much your software costs. The more costly the software the longer the time-lag.</p>
<p>Once you start making sales, there will be seasonal variations in how much money comes in. Always try and keep at least 6 months worth of money in the bank to cover salary and operating costs. </p></li>
<li><p><strong>Not knowing who your customers are</strong> - Once you start selling software, make sure you know who your customers are - they might be different from what you thought they were. When I started my software company, I thought my customers would be all R&D engineers who were doing research in magnetic layers. After a while it became clear that most of my users were the subset of this group that couldn't program, but understood the physics behind the software.</p></li>
<li><p><strong>Not acting in a professional manner</strong> - When interacting with customers be professional - act and dress in a professional manner.</p></li>
</ol> |
231,125 | Should I index a bit field in SQL Server? | <p>I remember reading at one point that indexing a field with low cardinality (a low number of distinct values) is not really worth doing. I admit I don't know enough about how indexes work to understand why that is.</p>
<p>So what if I have a table with 100 million rows in it, and I am selecting records where a bit field is 1? And let's say that at any point in time, there are only a handful of records where the bit field is 1 (as opposed to 0). Is it worth indexing that bit field or not? Why?</p>
<p>Of course I can just test it and check the execution plan, and I will do that, but I'm also curious about the theory behind it. When does cardinality matter and when does it not?</p> | 231,423 | 18 | 11 | null | 2008-10-23 19:31:53.4 UTC | 23 | 2019-03-07 10:22:10.303 UTC | 2008-10-23 21:30:32.427 UTC | Jeremy McCollum | 1,436 | Jeremy McCollum | 1,436 | null | 1 | 120 | sql-server|indexing | 41,878 | <p>Consider what an index is in SQL - and index is really a chunk of memory pointing at other chunks of memory (i.e. pointers to rows). The index is broken into pages so that portions of the index can be loaded and unloaded from memory depending on usage.</p>
<p>When you ask for a set of rows, SQL uses the index to find the rows more quickly than table scanning (looking at every row).</p>
<p>SQL has clustered and non-clustered indexes. My understanding of clustered indexes is that they group similar index values into the same page. This way when you ask for all the rows matching an index value, SQL can return those rows from a clustered page of memory. This is why trying to cluster index a GUID column is a bad idea - you don't try to cluster random values.</p>
<p>When you index an integer column, SQL's index contains a set of rows for each index value. If you have a range of 1 to 10, then you would have 10 index pointers. Depending on how many rows there are this can be paged differently. If your query looks for the index matching "1" and then where Name contains "Fred" (assuming the Name column is not indexed), SQL gets the set of rows matching "1" very quickly, then table scans to find the rest.</p>
<p>So what SQL is really doing is trying to reduce the working set (number of rows) it has to iterate over. </p>
<p>When you index a bit field (or some narrow range), you only reduce the working set by the number of rows matching that value. If you have a small number of rows matching it would reduce your working set a lot. For a large number of rows with 50/50 distribution, it might buy you very little performance gain vs. keeping the index up to date.</p>
<p>The reason everyone says to test is because SQL contains a very clever and complex optimizer that may ignore an index if it decides table scanning is faster, or may use a sort, or may organize memory pages however it darn well likes. </p> |
1,201,194 | PHP Getting Domain Name From Subdomain | <p>I need to write a function to parse variables which contain domain names. It's best I explain this with an example, the variable could contain any of these things:</p>
<pre><code>here.example.com
example.com
example.org
here.example.org
</code></pre>
<p>But when passed through my function all of these must return either example.com or example.co.uk, the root domain name basically. I'm sure I've done this before but I've been searching Google for about 20 minutes and can't find anything. Any help would be appreciated.</p>
<p>EDIT: Ignore the .co.uk, presume that all domains going through this function have a 3 letter TLD.</p> | 1,201,210 | 25 | 6 | null | 2009-07-29 15:41:25.413 UTC | 9 | 2022-04-20 04:49:51.147 UTC | 2009-07-29 15:57:41.2 UTC | null | 26,823 | null | 26,823 | null | 1 | 32 | php|dns|subdomain | 48,224 | <h3>Stackoverflow Question Archive:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/569137/how-to-get-domain-name-from-url/569219">How to get domain name from url?</a></li>
<li><a href="https://stackoverflow.com/questions/1122261/php-check-if-domain-equals-value-then-perform-action">Check if domain equals value?</a></li>
<li><a href="https://stackoverflow.com/questions/1144856/how-do-i-split-serverhttpreferer-to-get-the-base-url">How do I get the base url?</a></li>
</ul>
<hr />
<pre><code>print get_domain("http://somedomain.co.uk"); // outputs 'somedomain.co.uk'
function get_domain($url)
{
$pieces = parse_url($url);
$domain = isset($pieces['host']) ? $pieces['host'] : '';
if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
return $regs['domain'];
}
return false;
}
</code></pre> |
579,196 | Getting the last revision number in SVN? | <p>Using PHP, Perl, or Python (preferably PHP), I need a way to query an SVN database and find out the last revision number sent to SVN. I don't need anything other than that. It needs to be non-intensive (so I do it every 5 minutes as a cron job; SVN's performance should not be affected).</p>
<p>SVN is located on my Intranet, but not my specific computer.</p>
<p>I have SVN installed, but no bindings installed for PHP/Perl/Python. I'm running Windows XP, but I would prefer a platform-independent solution that can also work in Linux. If you have a Linux-only (or XP-only) solution, that would also be helpful.</p> | 579,238 | 26 | 4 | null | 2009-02-23 20:29:30.233 UTC | 32 | 2020-06-12 04:52:35.207 UTC | 2014-05-05 17:26:08.207 UTC | brian d foy | 321,731 | Coltin | 66,167 | null | 1 | 109 | svn | 250,052 | <pre class="lang-php prettyprint-override"><code><?php
$url = 'your repository here';
$output = `svn info $url`;
echo "<pre>$output</pre>";
?>
</code></pre>
<p>You can get the output in XML like so:</p>
<pre class="lang-php prettyprint-override"><code>$output = `svn info $url --xml`;
</code></pre>
<p>If there is an error then the output will be directed to stderr. To capture stderr in your output use thusly: </p>
<pre class="lang-php prettyprint-override"><code>$output = `svn info $url 2>&1`;
</code></pre> |
765,867 | List of all index & index columns in SQL Server DB | <p>How do I get a list of all index & index columns in SQL Server 2005+? The closest I could get is:</p>
<pre><code>select s.name, t.name, i.name, c.name from sys.tables t
inner join sys.schemas s on t.schema_id = s.schema_id
inner join sys.indexes i on i.object_id = t.object_id
inner join sys.index_columns ic on ic.object_id = t.object_id
inner join sys.columns c on c.object_id = t.object_id and
ic.column_id = c.column_id
where i.index_id > 0
and i.type in (1, 2) -- clustered & nonclustered only
and i.is_primary_key = 0 -- do not include PK indexes
and i.is_unique_constraint = 0 -- do not include UQ
and i.is_disabled = 0
and i.is_hypothetical = 0
and ic.key_ordinal > 0
order by ic.key_ordinal
</code></pre>
<p>Which is not exactly what I want.<br>
What I want is, to list all user-defined indexes, (<em>which means no indexes which support unique constraints & primary keys</em>) with all columns (ordered by how do they appear in index definition) plus as much metadata as possible.</p> | 765,892 | 30 | 3 | null | 2009-04-19 18:38:24.623 UTC | 154 | 2022-05-16 13:53:05.27 UTC | 2016-09-28 12:46:30.58 UTC | null | 3,682,162 | null | 60,188 | null | 1 | 390 | sql-server|tsql|indexing|reverse-engineering | 782,021 | <p>There are two "sys" catalog views you can consult: <code>sys.indexes</code> and <code>sys.index_columns</code>.</p>
<p>Those will give you just about any info you could possibly want about indices and their columns.</p>
<p>EDIT: This query's getting pretty close to what you're looking for:</p>
<pre><code>SELECT
TableName = t.name,
IndexName = ind.name,
IndexId = ind.index_id,
ColumnId = ic.index_column_id,
ColumnName = col.name,
ind.*,
ic.*,
col.*
FROM
sys.indexes ind
INNER JOIN
sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id
INNER JOIN
sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id
INNER JOIN
sys.tables t ON ind.object_id = t.object_id
WHERE
ind.is_primary_key = 0
AND ind.is_unique = 0
AND ind.is_unique_constraint = 0
AND t.is_ms_shipped = 0
ORDER BY
t.name, ind.name, ind.index_id, ic.is_included_column, ic.key_ordinal;
</code></pre> |
6,458,423 | Is there a cleaner way to pattern-match in Scala anonymous functions? | <p>I find myself writing code like the following:</p>
<pre><code>val b = a map (entry =>
entry match {
case ((x,y), u) => ((y,x), u)
}
)
</code></pre>
<p>I would like to write it differently, if only this worked:</p>
<pre><code>val c = a map (((x,y) -> u) =>
(y,x) -> u
)
</code></pre>
<p>Is there any way I can get something close to this?</p> | 6,458,477 | 4 | 0 | null | 2011-06-23 17:49:52.103 UTC | 14 | 2019-12-26 21:23:01.163 UTC | null | null | null | null | 371,739 | null | 1 | 46 | scala|pattern-matching | 33,925 | <p>Believe it or not, this works:</p>
<pre><code>val b = List(1, 2)
b map {
case 1 => "one"
case 2 => "two"
}
</code></pre>
<p>You can skip the <code>p => p match</code> in simple cases. So this should work:</p>
<pre><code>val c = a map {
case ((x,y) -> u) => (y,x) -> u
}
</code></pre> |
6,798,867 | Android: How to Programmatically set the size of a Layout | <p>As part of an Android App I am building a button set. The buttons are part of a nested set of LinearLayouts. Using weight I have the set resizing itself automatically based on the size of the containing parent LinearLayout. The idea is, based on the pixel count and density of the screen, to set the size of the containing layout to a number of pixels; and have the button set resize itself based on that change.</p>
<p>The question then is: How to resize the layout. </p>
<p>I have tried several suggested techniques, and none come close to working. Here is a subset of the XML that builds the button set:</p>
<pre><code> <LinearLayout android:layout_height="104pt" android:id="@+id/numberPadLayout" android:orientation="horizontal" android:layout_width="104pt"
android:background="#a0a0a0"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
>
<LinearLayout android:layout_weight="2" android:layout_height="fill_parent" android:id="@+id/linearLayout1" android:orientation="vertical" android:layout_width="wrap_content">
<Button android:text="1" android:id="@+id/button1" android:layout_weight="2" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
<Button android:text="4" android:id="@+id/button4" android:layout_weight="2" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
<Button android:text="7" android:id="@+id/button7" android:layout_weight="2" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
<Button android:text="-" android:id="@+id/buttonDash" android:layout_weight="2" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
</LinearLayout>
<LinearLayout android:layout_weight="2" android:layout_height="fill_parent" android:id="@+id/linearLayout2" android:orientation="vertical" android:layout_width="wrap_content">
<Button android:text="2" android:id="@+id/button2" android:layout_weight="2" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
<Button android:text="5" android:id="@+id/button5" android:layout_weight="2" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
<Button android:text="8" android:id="@+id/button8" android:layout_weight="2" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
<Button android:text="0" android:id="@+id/button0" android:layout_weight="2" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
</LinearLayout>
<LinearLayout android:layout_weight="2" android:layout_height="fill_parent" android:id="@+id/linearLayout3" android:orientation="vertical" android:layout_width="wrap_content">
<Button android:text="3" android:id="@+id/button3" android:layout_weight="2" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
<Button android:text="6" android:id="@+id/button6" android:layout_weight="2" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
<Button android:text="9" android:id="@+id/button9" android:layout_weight="2" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
<Button android:text="." android:id="@+id/buttonDot" android:layout_weight="2" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
</LinearLayout>
<LinearLayout android:layout_weight="2" android:layout_height="fill_parent" android:id="@+id/linearLayout4" android:orientation="vertical" android:layout_width="wrap_content">
<Button android:text="/" android:id="@+id/buttonBack" android:layout_weight="2" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
<Button android:text="\" android:id="@+id/buttonEnter" android:layout_weight="2" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
</LinearLayout>
</LinearLayout>
</code></pre>
<p>The two questions are: 1) how do I get access to numberPadLayout from Java. And once I have access to the view, 2) how do I change the height and width of the layout.</p>
<p>Any suggestions will be appreciated.</p> | 6,798,938 | 4 | 0 | null | 2011-07-23 07:02:06.277 UTC | 56 | 2019-07-29 20:45:37.56 UTC | null | null | null | null | 845,543 | null | 1 | 162 | android|layout|resize|android-linearlayout | 319,319 | <h2>Java</h2>
<p>This should work:</p>
<pre><code>// Gets linearlayout
LinearLayout layout = findViewById(R.id.numberPadLayout);
// Gets the layout params that will allow you to resize the layout
LayoutParams params = layout.getLayoutParams();
// Changes the height and width to the specified *pixels*
params.height = 100;
params.width = 100;
layout.setLayoutParams(params);
</code></pre>
<p>If you want to convert dip to pixels, use this:</p>
<pre><code>int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, <HEIGHT>, getResources().getDisplayMetrics());
</code></pre>
<h2><a href="https://stackoverflow.com/a/57259721/5279996">Kotlin</a></h2> |
6,567,500 | MySQL: making a column unique? | <p>I have a table that is in production. I realize that some of the columns should be unique. Is it safe to go into phpMyAdmin and change those columns to make it unique?</p>
<pre><code>ALTER TABLE `foo` ADD UNIQUE ( `bar` )
</code></pre> | 6,567,551 | 5 | 2 | null | 2011-07-04 05:09:55.717 UTC | 4 | 2020-03-03 17:23:15.657 UTC | 2011-07-04 05:14:45.21 UTC | null | 135,152 | null | 253,976 | null | 1 | 25 | mysql|phpmyadmin|unique-constraint | 69,401 | <ol>
<li>You do not have duplicates -> will apply the key without issues</li>
<li>You do have duplicates -> will give an error message, nothing happened to your data</li>
<li>All is unique, except several rows with NULL in them, unique constraint is still applied, as NULL is not checked when checking for unique values (you can have the entire table have a NULL value in a unique field without any error message).</li>
</ol>
<p>One more thing, if you have a prod DB, you must also have a dev DB which you can test on without fear, right?</p> |
6,362,688 | jQuery check if Cookie exists, if not create it | <p>I cannot get this code to work I must be missing something pretty simple. I am trying to check to see if a Cookie exists, if it does {do nothing} if it doesn't {create it}. I am testing the cookie by including an alert on a page. Basically I do not want the cookie to keep re-creating with a referral url, I am trying to grab only the FIRST referred URL.</p>
<pre><code>$(document).ready(function(){
if ($.cookie('bas_referral') == null ){
var ref = document.referrer.toLowerCase();
// set cookie
var cookURL = $.cookie('bas_referral', ref, { expires: 1 });
}
});
</code></pre>
<p>Displaying the current cookie contents:</p>
<pre><code> // get cookie
alert($.cookie('bas_referral'));
// delete cookie
$.cookie('bas_referral', null);
</code></pre> | 23,344,706 | 5 | 3 | null | 2011-06-15 18:44:19.09 UTC | 10 | 2018-04-27 04:14:16.443 UTC | null | null | null | null | 525,706 | null | 1 | 42 | jquery|cookies|if-statement|referrer|isnull | 170,628 | <p>I think the bulletproof way is:</p>
<pre><code>if (typeof $.cookie('token') === 'undefined'){
//no cookie
} else {
//have cookie
}
</code></pre>
<p>Checking the type of a null, empty or undefined var always returns 'undefined'</p>
<p><strong>Edit:</strong>
You can get there even easier:</p>
<pre><code>if (!!$.cookie('token')) {
// have cookie
} else {
// no cookie
}
</code></pre>
<p><code>!!</code> will turn the <a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy" rel="noreferrer"><em>falsy</em> values</a> to false. Bear in mind that this will turn <code>0</code> to false!</p> |
6,339,480 | How to detect if a browser is Chrome using jQuery? | <p>I have a bit of an issue with a function running in chrome that works properly in Safari, both webkit browsers...</p>
<p>I need to customize a variable in a function for Chrome, but not for Safari.</p>
<p>Sadly, I have been using this to detect if it is a webkit browser:</p>
<pre><code>if ($.browser.webkit) {
</code></pre>
<p>But I need to detect:</p>
<pre><code>if ($.browser.chrome) {
</code></pre>
<p>Is there any way to write a similar statement (a working version of the one above)?</p> | 6,339,535 | 11 | 5 | null | 2011-06-14 05:32:44.137 UTC | 12 | 2019-03-01 12:20:17.037 UTC | 2011-06-22 10:17:54.977 UTC | null | 179,573 | null | 720,785 | null | 1 | 57 | jquery|jquery-ui|google-chrome|jquery-selectors|cross-browser | 112,223 | <pre><code>$.browser.chrome = /chrom(e|ium)/.test(navigator.userAgent.toLowerCase());
if($.browser.chrome){
............
}
</code></pre>
<p><strong>UPDATE:(10x to @Mr. Bacciagalupe)</strong></p>
<p>jQuery has removed <code>$.browser</code> from <strong>1.9</strong> and their latest release. </p>
<p>But you can still use $.browser as a standalone plugin, found <a href="https://github.com/gabceb/jquery-browser-plugin">here</a> </p> |
15,726,197 | Parsing a JSON array using Json.Net | <p>I'm working with Json.Net to parse an array. What I'm trying to do is to pull the name/value pairs out of the array and assign them to specific variables while parsing the JObject. </p>
<p>Here's what I've got in the array:</p>
<pre><code>[
{
"General": "At this time we do not have any frequent support requests."
},
{
"Support": "For support inquires, please see our support page."
}
]
</code></pre>
<p>And here's what I've got in the C#:</p>
<pre><code>WebRequest objRequest = HttpWebRequest.Create(dest);
WebResponse objResponse = objRequest.GetResponse();
using (StreamReader reader = new StreamReader(objResponse.GetResponseStream()))
{
string json = reader.ReadToEnd();
JArray a = JArray.Parse(json);
//Here's where I'm stumped
}
</code></pre>
<p>I'm fairly new to JSON and Json.Net, so it might be a basic solution for someone else. I basically just need to assign the name/value pairs in a foreach loop so that I can output the data on the front-end. Has anyone done this before? </p> | 15,726,500 | 3 | 0 | null | 2013-03-31 04:01:36.83 UTC | 21 | 2021-04-09 13:11:35.487 UTC | 2015-12-20 01:41:16.773 UTC | null | 10,263 | null | 1,745,143 | null | 1 | 59 | c#|asp.net|json|json.net | 127,120 | <p>You can get at the data values like this:</p>
<pre><code>string json = @"
[
{ ""General"" : ""At this time we do not have any frequent support requests."" },
{ ""Support"" : ""For support inquires, please see our support page."" }
]";
JArray a = JArray.Parse(json);
foreach (JObject o in a.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
string value = (string)p.Value;
Console.WriteLine(name + " -- " + value);
}
}
</code></pre>
<p>Fiddle: <a href="https://dotnetfiddle.net/uox4Vt" rel="noreferrer">https://dotnetfiddle.net/uox4Vt</a></p> |
16,001,586 | Change the "No file chosen": | <p>I have a button "Choose file" as follows (I am using Jade but it should be the same as Html5):</p>
<pre><code> input(type='file', name='videoFile')
</code></pre>
<p>In the browser this shows a button with a text next to it "No file chosen". I would like to change the "No file chosen" text to something else, like "No video chosen" or "Choose a video please". I followed the first suggestions here:</p>
<p><a href="https://stackoverflow.com/questions/5927212/i-dont-want-to-see-no-file-chosen-for-a-file-input-field">I don't want to see 'no file chosen' for a file input field</a></p>
<p>But doing this did not change the text:</p>
<pre><code> input(type='file', name='videoFile', title = "Choose a video please")
</code></pre>
<p>Can anybody help me figure out where the problem is?</p> | 16,001,704 | 23 | 5 | null | 2013-04-14 16:48:59.7 UTC | 28 | 2022-08-24 06:53:07.347 UTC | 2017-05-23 10:31:28.05 UTC | null | -1 | null | 1,181,847 | null | 1 | 126 | html|button|file-upload|pug | 361,636 | <p>I'm pretty sure you cannot change the default labels on buttons, they are hard-coded in browsers (each browser rendering the buttons captions its own way). Check out this <a href="http://www.quirksmode.org/dom/inputfile.html">button styling article</a></p> |
15,974,730 | How do I get the different parts of a Flask request's url? | <p>I want to detect if the request came from the <code>localhost:5000</code> or <code>foo.herokuapp.com</code> host and what path was requested. How do I get this information about a Flask request?</p> | 15,975,041 | 4 | 0 | null | 2013-04-12 15:02:05.797 UTC | 69 | 2022-07-21 11:41:12.61 UTC | 2015-07-28 20:50:02.23 UTC | null | 400,617 | null | 1,544,125 | null | 1 | 209 | python|url|flask | 190,471 | <p>You can examine the url through several <a href="http://flask.pocoo.org/docs/api/#flask.Request.path" rel="noreferrer"><code>Request</code></a> fields:</p>
<blockquote>
<p>Imagine your application is listening on the following application root:</p>
<pre><code>http://www.example.com/myapplication
</code></pre>
<p>And a user requests the following URI:</p>
<pre><code>http://www.example.com/myapplication/foo/page.html?x=y
</code></pre>
<p>In this case the values of the above mentioned attributes would be the following:</p>
<pre><code> path /foo/page.html
full_path /foo/page.html?x=y
script_root /myapplication
base_url http://www.example.com/myapplication/foo/page.html
url http://www.example.com/myapplication/foo/page.html?x=y
url_root http://www.example.com/myapplication/
</code></pre>
</blockquote>
<p>You can easily extract the host part with the appropriate splits.</p>
<p>An example of using this:</p>
<pre><code>from flask import request
@app.route('/')
def index():
return request.base_url
</code></pre> |
32,705,582 | How to get time.Tick to tick immediately | <p>I have a loop that iterates until a job is up and running:</p>
<pre><code>ticker := time.NewTicker(time.Second * 2)
defer ticker.Stop()
started := time.Now()
for now := range ticker.C {
job, err := client.Job(jobID)
switch err.(type) {
case DoesNotExistError:
continue
case InternalError:
return err
}
if job.State == "running" {
break
}
if now.Sub(started) > time.Minute*2 {
return fmt.Errorf("timed out waiting for job")
}
}
</code></pre>
<p>Works great in production. The only problem is that it makes my tests slow. They all wait at least 2 seconds before completing. Is there anyway to get <code>time.Tick</code> to tick immediately?</p> | 54,752,803 | 6 | 6 | null | 2015-09-21 22:35:32.41 UTC | 9 | 2020-12-15 06:02:43.627 UTC | 2015-09-22 07:21:08.213 UTC | null | 53,926 | null | 53,926 | null | 1 | 33 | go|timer | 17,557 | <p>Unfortunately, it <a href="https://github.com/golang/go/issues/17601" rel="noreferrer">seems</a> that Go developers will not add such functionality in any foreseeable future, so we have to cope...</p>
<p>There are two common ways to use tickers:</p>
<h2><code>for</code> loop</h2>
<p>Given something like this:</p>
<pre class="lang-golang prettyprint-override"><code>ticker := time.NewTicker(period)
defer ticker.Stop()
for <- ticker.C {
...
}
</code></pre>
<p>Use:</p>
<pre class="lang-golang prettyprint-override"><code>ticker := time.NewTicker(period)
defer ticker.Stop()
for ; true; <- ticker.C {
...
}
</code></pre>
<h2><code>for</code>-<code>select</code> loop</h2>
<p>Given something like this:</p>
<pre class="lang-golang prettyprint-override"><code>interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
ticker := time.NewTicker(period)
defer ticker.Stop()
loop:
for {
select {
case <- ticker.C:
f()
case <- interrupt:
break loop
}
}
</code></pre>
<p>Use:</p>
<pre class="lang-golang prettyprint-override"><code>interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
ticker := time.NewTicker(period)
defer ticker.Stop()
loop:
for {
f()
select {
case <- ticker.C:
continue
case <- interrupt:
break loop
}
}
</code></pre>
<h2>Why not just use <code>time.Tick()</code>?</h2>
<blockquote>
<p>While Tick is useful for clients that have no need to shut down the Ticker, be aware that without a way to shut it down the underlying Ticker cannot be recovered by the garbage collector; it "leaks".</p>
</blockquote>
<p><a href="https://golang.org/pkg/time/#Tick" rel="noreferrer">https://golang.org/pkg/time/#Tick</a></p> |
10,359,485 | How to download and unzip a zip file in memory in NodeJs? | <p>I want to download a zip file from the internet and unzip it in memory without saving to a temporary file. How can I do this?</p>
<p>Here is what I tried:</p>
<pre><code>var url = 'http://bdn-ak.bloomberg.com/precanned/Comdty_Calendar_Spread_Option_20120428.txt.zip';
var request = require('request'), fs = require('fs'), zlib = require('zlib');
request.get(url, function(err, res, file) {
if(err) throw err;
zlib.unzip(file, function(err, txt) {
if(err) throw err;
console.log(txt.toString()); //outputs nothing
});
});
</code></pre>
<p>[EDIT]
As, suggested, I tried using the adm-zip library and I still cannot make this work:</p>
<pre><code>var ZipEntry = require('adm-zip/zipEntry');
request.get(url, function(err, res, zipFile) {
if(err) throw err;
var zip = new ZipEntry();
zip.setCompressedData(new Buffer(zipFile.toString('utf-8')));
var text = zip.getData();
console.log(text.toString()); // fails
});
</code></pre> | 10,391,641 | 4 | 5 | null | 2012-04-28 00:31:22.293 UTC | 22 | 2018-11-22 08:03:41.987 UTC | 2012-04-30 20:21:42.75 UTC | null | 471,136 | null | 471,136 | null | 1 | 52 | javascript|node.js|zip|zlib|unzip | 68,353 | <p>You need a library that can handle buffers. The latest version of <code>adm-zip</code> will do:</p>
<pre><code>npm install adm-zip
</code></pre>
<p>My solution uses the <code>http.get</code> method, since it returns Buffer chunks. </p>
<p>Code:</p>
<pre><code>var file_url = 'http://notepad-plus-plus.org/repository/7.x/7.6/npp.7.6.bin.x64.zip';
var AdmZip = require('adm-zip');
var http = require('http');
http.get(file_url, function(res) {
var data = [], dataLen = 0;
res.on('data', function(chunk) {
data.push(chunk);
dataLen += chunk.length;
}).on('end', function() {
var buf = Buffer.alloc(dataLen);
for (var i = 0, len = data.length, pos = 0; i < len; i++) {
data[i].copy(buf, pos);
pos += data[i].length;
}
var zip = new AdmZip(buf);
var zipEntries = zip.getEntries();
console.log(zipEntries.length)
for (var i = 0; i < zipEntries.length; i++) {
if (zipEntries[i].entryName.match(/readme/))
console.log(zip.readAsText(zipEntries[i]));
}
});
});
</code></pre>
<p>The idea is to create an array of buffers and concatenate them into a new one at the end. This is due to the fact that buffers cannot be resized.</p>
<p><strong>Update</strong></p>
<p>This is a simpler solution that uses the <code>request</code> module to obtain the response in a buffer, by setting <code>encoding: null</code> in the options. It also follows redirects and resolves http/https automatically.</p>
<pre><code>var file_url = 'https://github.com/mihaifm/linq/releases/download/3.1.1/linq.js-3.1.1.zip';
var AdmZip = require('adm-zip');
var request = require('request');
request.get({url: file_url, encoding: null}, (err, res, body) => {
var zip = new AdmZip(body);
var zipEntries = zip.getEntries();
console.log(zipEntries.length);
zipEntries.forEach((entry) => {
if (entry.entryName.match(/readme/i))
console.log(zip.readAsText(entry));
});
});
</code></pre>
<p>The <code>body</code> of the response is a buffer that can be passed directly to <code>AdmZip</code>, simplifying the whole process.</p> |
31,708,519 | Request returns bytes and I'm failing to decode them | <p>Essentially I made a request to a website and got a byte response back: <code>b'[{"geonameId:"703448"}..........'.</code> I'm confused because although it is of type byte, it is very human readable and appears like a list of json. I do know that the response is encoded in latin1 from running <code>r.encoding</code> which returned <code>ISO-859-1</code> and I have tried to decode it, but it just returns an empty string. Here's what I have so far:</p>
<pre><code>r = response.content
string = r.decode("ISO-8859-1")
print (string)
</code></pre>
<p>and this is where it prints a blank line.
However when I run </p>
<pre><code>len(string)
</code></pre>
<p>I get: back <code>31023</code>
How can I decode these bytes without getting back an empty string?</p> | 31,709,042 | 4 | 2 | null | 2015-07-29 18:35:12.633 UTC | 6 | 2022-08-11 02:51:33.66 UTC | 2015-07-29 18:44:43.03 UTC | null | 5,170,642 | null | 5,170,642 | null | 1 | 37 | python|json|byte|python-requests|decoding | 68,052 | <p>Did you try to parse it with the <code>json</code> module?</p>
<pre><code>import json
parsed = json.loads(response.content)
</code></pre> |
33,892,546 | How to get profile like gender from google signin in Android? | <p>I want to integrate google sign in to my app, when user first sign in I will create an account bind to this, so I need some profiles like gender, locale, etc.
and I tried as the google-sign-in doc and quick-start sample shows:</p>
<pre><code>GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
</code></pre>
<p>when click to sign in I will call:</p>
<pre><code> Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
</code></pre>
<p>sign in successful, I can get a data structure GoogleSignInResult in onActivityResult, from GoogleSignInResult I can get a GoogleSignInAccount, which only contains DisplayName, email and id.
but when in <a href="https://developers.google.com/apis-explorer/#p/" rel="noreferrer">https://developers.google.com/apis-explorer/#p/</a>, I can get profiles like gender, locale. Is there anything I missed?</p>
<p>and I tried google plus api, it seems that I can get what I want. but don't know how to use, the doc says create client like this:</p>
<pre><code>mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(new Scope(Scopes.PLUS_LOGIN))
.addScope(new Scope(Scopes.PLUS_ME))
.build();
</code></pre>
<p>but when I use this, click signin button will cause app crash.</p>
<p><strong>Update:</strong> problems when update to new version of google sign in <a href="https://stackoverflow.com/questions/37317295/missing-api-key-current-key-with-google-services-3-0-0/37520198#37520198">Missing api_key/current key with Google Services 3.0.0</a></p> | 33,906,880 | 5 | 7 | null | 2015-11-24 11:32:43.25 UTC | 13 | 2019-01-05 10:59:49.96 UTC | 2017-05-23 12:18:08.593 UTC | null | -1 | null | 3,628,097 | null | 1 | 26 | android|google-signin|google-plus-signin | 30,033 | <p><em>UPDATE:</em> </p>
<p>Since <strong>Plus.PeopleApi</strong> has been deprecated in Google Play services 9.4 as <a href="https://developers.google.com/+/mobile/android/api-deprecation" rel="noreferrer">Google's declaration notes</a>, please refer to the following solutions using <a href="https://developers.google.com/people/" rel="noreferrer">Google People API</a> instead:</p>
<blockquote>
<p><a href="https://stackoverflow.com/questions/33814103/get-person-details-in-new-google-sign-in-play-services-8-3/39171650#39171650">Get person details in new google sign in Play Services 8.3</a>
(Isabella Chen's answer);</p>
<p><a href="https://stackoverflow.com/questions/37962724/cannot-get-private-birthday-from-google-plus-account-although-explicit-request">Cannot get private birthday from Google Plus account although explicit request</a></p>
</blockquote>
<p><em>END OF UPDATE</em></p>
<hr>
<p>First of all, make sure you have created Google+ profile for your Google account. Then you can refer to the following code:</p>
<pre><code>GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(new Scope(Scopes.PLUS_LOGIN))
.requestEmail()
.build();
</code></pre>
<p>and</p>
<pre><code>mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.addApi(Plus.API)
.build();
</code></pre>
<p>Then</p>
<pre><code> @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
// G+
Person person = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
Log.i(TAG, "--------------------------------");
Log.i(TAG, "Display Name: " + person.getDisplayName());
Log.i(TAG, "Gender: " + person.getGender());
Log.i(TAG, "AboutMe: " + person.getAboutMe());
Log.i(TAG, "Birthday: " + person.getBirthday());
Log.i(TAG, "Current Location: " + person.getCurrentLocation());
Log.i(TAG, "Language: " + person.getLanguage());
}
}
</code></pre>
<p>Inside <code>build.gradle</code> file</p>
<pre><code>// Dependency for Google Sign-In
compile 'com.google.android.gms:play-services-auth:8.3.0'
compile 'com.google.android.gms:play-services-plus:8.3.0'
</code></pre>
<p>You can take a look at <a href="https://github.com/ngocchung/GoogleSignInDemo" rel="noreferrer">My GitHub sample project</a>. Hope this helps!</p> |
13,366,249 | call_user_func() expects parameter 1 to be a valid callback | <p>I'm just playing around with the call_user_func function in PHP and am getting this error when running this simple code:</p>
<pre><code><?php
class A
{
public $var;
private function printHi()
{
echo "Hello";
}
public function __construct($string)
{
$this->var = $string;
}
public function foo()
{
call_user_func($this->var);
}
}
$a = new A('printHi');
$a->foo();
?>
</code></pre>
<p>I know that if I make a function outside the class called printHi, it works fine, but I'm referring to the class's print hi and not sure why the "this" isn't being registered.</p> | 13,366,296 | 2 | 1 | null | 2012-11-13 18:09:30.303 UTC | 2 | 2017-08-04 10:35:00.2 UTC | null | null | null | null | 1,316,465 | null | 1 | 16 | php|dictionary | 88,849 | <p><code>$this->var</code> is evaluating to <code>printHi</code> in your example. However, when you are calling a method of a class, you need to pass the callback as an array where the first element is the object instance and the second element is the function name:</p>
<pre><code>call_user_func(array($this, $this->var));
</code></pre>
<p>Here is the documentation on valid callbacks: <a href="http://www.php.net/manual/en/language.types.callable.php" rel="noreferrer">http://www.php.net/manual/en/language.types.callable.php</a></p> |
13,637,814 | Maximum number of lines for a Wrap TextBlock | <p>I have a <code>TextBlock</code> with the following setting:</p>
<pre><code>TextWrapping="Wrap"
</code></pre>
<p>Can I determine the maximum number of lines?</p>
<p>for example consider the following string <code>TextBlock.Text</code>:</p>
<pre><code>This is a very good horse under the blackboard!!
</code></pre>
<p>It currently has been shows like this:</p>
<pre><code>This is a very
good horse under
the blackboard!!
</code></pre>
<p>I need that to become something like:</p>
<pre><code>This is a very
good horse ...
</code></pre>
<p>any solution?</p> | 20,080,779 | 7 | 0 | null | 2012-11-30 01:44:39.257 UTC | 5 | 2021-04-27 15:18:22.257 UTC | 2020-05-05 19:24:32.15 UTC | null | 3,195,477 | null | 395,573 | null | 1 | 32 | xaml|uwp|windows-8|uwp-xaml|textblock | 22,286 | <h1>Update (for UWP)</h1>
<p>In UWP Apps you don't need this and can use the TextBlock property <code>MaxLines</code> (see <a href="https://msdn.microsoft.com/de-de/library/windows/apps/windows.ui.xaml.controls.textblock.maxlines" rel="noreferrer">MSDN</a>)</p>
<hr>
<h1>Original Answer:</h1>
<p>If you have a specific <code>LineHeight</code> you can calculate the <strong>maximum height</strong> for the TextBlock.</p>
<h3>Example:</h3>
<p><em>TextBlock with maximum 3 lines</em></p>
<pre><code><TextBlock
Width="300"
TextWrapping="Wrap"
TextTrimming="WordEllipsis"
FontSize="24"
LineStackingStrategy="BlockLineHeight"
LineHeight="28"
MaxHeight="84">YOUR TEXT</TextBlock>
</code></pre>
<p>This is all that you need to get your requirement working.</p>
<h3>How to do this dynamically?</h3>
<p>Just create a new control in C#/VB.NET that extends <code>TextBlock</code> and give it a new <code>DependencyProperty</code> <em>int MaxLines</em>.
<br>Then override the <code>OnApplyTemplate()</code> method and set the <code>MaxHeight</code> based on the <code>LineHeight</code> * <code>MaxLines</code>.</p>
<p>That's just a basic explanation on how you could solve this problem!</p> |
13,464,540 | Skip to next modified file in git diff? | <p>I made the mistake of upgrading a Visual Studio project from 2008 to 2010 without checking in my previous changes first. Because of this I have a huge system generated file (10k+ lines) that had every 4th line changed.</p>
<p>I'm usually pretty good about checking in stuff often, so I will typically just use the down key to scroll through my changes. In this case it will take several lifetimes to scroll through the changes to the system generated file.</p>
<p>Is there a way to skip to the next modified file after you have done a <code>git diff</code> so that you don't have to scroll through every change on every file?</p> | 13,464,561 | 6 | 2 | null | 2012-11-19 23:57:00.23 UTC | 14 | 2021-12-16 17:03:29.59 UTC | null | null | null | null | 226,897 | null | 1 | 56 | git | 18,663 | <p>By default, <code>git diff</code> pipes its output through <code>less</code>. So you can use the <code>less</code> commands to search for the next header. Type <code>/^diff</code> and press <kbd>Enter</kbd> to skip to the next file.</p> |
3,597,743 | Where is ptrdiff_t defined in C? | <p>Where is <code>ptrdiff_t</code> defined in C?</p> | 3,597,749 | 2 | 0 | null | 2010-08-30 03:48:59.027 UTC | 7 | 2020-01-20 09:55:34.857 UTC | 2020-01-20 09:55:34.857 UTC | null | 545,127 | null | 149,482 | null | 1 | 58 | c|types|libc|stdint | 31,311 | <p>It's defined in <code>stddef.h</code>.</p>
<hr>
<p>That header defines the integral types <code>size_t</code>, <code>ptrdiff_t</code>, and <code>wchar_t</code>, the functional macro <code>offsetof</code>, and the constant macro <code>NULL</code>.</p> |
28,507,619 | How to create delay function in QML? | <p>I would like to create a delay function in javascript that takes a parameter of amount of time to delay, so that I could use it do introduce delay between execution of JavaScript lines in my QML application. It would perhaps look like this:</p>
<pre><code>function delay(delayTime) {
// code to create delay
}
</code></pre>
<p>I need the body of the function <code>delay()</code>. Note that <code>setTimeout()</code> of JavaScript doesn't work in QML.</p> | 28,514,691 | 6 | 4 | null | 2015-02-13 19:49:54.083 UTC | 14 | 2021-10-25 13:06:12.417 UTC | 2021-05-25 17:56:33.507 UTC | null | 3,375,713 | null | 3,375,713 | null | 1 | 39 | javascript|qml|delay | 41,151 | <p>As suggested in the comments to your question, the <a href="http://doc.qt.io/qt-5/qml-qtqml-timer.html">Timer</a> component is a good solution to this.</p>
<pre><code>function Timer() {
return Qt.createQmlObject("import QtQuick 2.0; Timer {}", root);
}
timer = new Timer();
timer.interval = 1000;
timer.repeat = true;
timer.triggered.connect(function () {
print("I'm triggered once every second");
})
timer.start();
</code></pre>
<p>The above would be how I'm currently using it, and here's how I might have implemented the example in your question.</p>
<pre><code>function delay(delayTime) {
timer = new Timer();
timer.interval = delayTime;
timer.repeat = false;
timer.start();
}
</code></pre>
<p>(Which doesn't do anything; read on)</p>
<p>Though the exact way you are looking for it to be implemented suggests that you are looking for it to <em>block</em> until the next line of your program executes. But this isn't a very good way to go about it as it would also block <em>everything else</em> in your program as JavaScript only runs in a single thread of execution. </p>
<p>An alternative is to pass a callback.</p>
<pre><code>function delay(delayTime, cb) {
timer = new Timer();
timer.interval = delayTime;
timer.repeat = false;
timer.triggered.connect(cb);
timer.start();
}
</code></pre>
<p>Which would allow you to use it as such.</p>
<pre><code>delay(1000, function() {
print("I am called one second after I was started.");
});
</code></pre>
<p>Hope it helps!</p>
<p>Edit: The above assumes you're working in a separate JavaScript file that you later import into your QML file. To do the equivalent in a QML file directly, you can do this.</p>
<pre><code>import QtQuick 2.0
Rectangle {
width: 800
height: 600
color: "brown"
Timer {
id: timer
}
function delay(delayTime, cb) {
timer.interval = delayTime;
timer.repeat = false;
timer.triggered.connect(cb);
timer.start();
}
Rectangle {
id: rectangle
color: "yellow"
anchors.fill: parent
anchors.margins: 100
opacity: 0
Behavior on opacity {
NumberAnimation {
duration: 500
}
}
}
Component.onCompleted: {
print("I'm printed right away..")
delay(1000, function() {
print("And I'm printed after 1 second!")
rectangle.opacity = 1
})
}
}
</code></pre>
<p>I'm not convinced that this is the solution to your actual problem however; to delay an animation, you could use <a href="http://doc.qt.io/qt-5/qml-qtquick-pauseanimation.html">PauseAnimation</a>.</p> |
9,631,246 | ssh key passphrase works in windows but not in linux | <p>I'm working to a project in git.
In Windows, I'm using git extensions to manage this project, and to access to the public repository they gave me a .ppk key. I load it into git extension, with the passphrase that they gave me, and it works.</p>
<p>Now I set a linux (ubuntu-32bit) virtual machine, and I want to access also from this machine to the repository.</p>
<p>From another thread that I've seen in this site, I use, to clone the repository, the following command:</p>
<pre><code>ssh-agent bash -c 'ssh-add /home/myHome/mykey.ppk; git clone git@serveraddress:project.git'
</code></pre>
<p>Then, the shell tells me to insert the passphrase</p>
<pre><code>Enter passphrase for /home/myHome/mykey.ppk:
</code></pre>
<p>But when I insert it, it tells me that's a bad passphrase. I've checked it a lot of times, and I'm sure that I use the same passphrase that I use in windows. So how can I use correctly the key in Linux?</p>
<p>Thanks in advance for your replies.</p> | 9,631,377 | 1 | 2 | null | 2012-03-09 08:55:33.403 UTC | 8 | 2014-03-11 10:28:34.223 UTC | null | null | null | null | 979,325 | null | 1 | 32 | git|ssh|passphrase | 18,359 | <p>The Linux SSH client (typically OpenSSH) can't read the PPK format used by the Windows SSH client Putty. You need to convert the "PPK" key given to you into an OpenSSH key first. Install "putty" on Linux and use the <code>puttygen</code> command line tool:</p>
<pre><code>$ sudo aptitude install putty
$ mkdir -p ~/.ssh
$ puttygen ~/mykey.ppk -o ~/.ssh/id_rsa -O private-openssh
</code></pre>
<p>Enter your passphrase, and you'll get an OpenSSH-compatible key in the standard location <code>~/.ssh/id_rsa</code>. Afterwards you can just use <code>ssh-add</code>(without any arguments!) to add this key to the SSH agent.</p>
<p>Alternatively you can use the PUTTYgen program provided by putty on Windows.</p> |
29,739,751 | Implementing a randomly generated maze using Prim's Algorithm | <p>I am trying to implement a randomly generated maze using Prim's algorithm.</p>
<p>I want my maze to look like this:
<img src="https://i.stack.imgur.com/AoNjK.png" alt="enter image description here"></p>
<p>however the mazes that I am generating from my program look like this:</p>
<p><img src="https://i.stack.imgur.com/WG7EV.png" alt="enter image description here"></p>
<p>I'm currently stuck on correctly implementing the steps highlighted in bold:</p>
<blockquote>
<ol>
<li>Start with a grid full of walls.</li>
<li>Pick a cell, mark it as part of the maze. Add the walls of the cell to the wall list.</li>
<li>While there are walls in the list:
<ul>
<li>**1. Pick a random wall from the list. If the cell on the opposite side isn't in the maze yet:
<ul>
<li><ol>
<li>Make the wall a passage and mark the cell on the opposite side as part of the maze.**</li>
</ol></li>
<li><ol start="2">
<li>Add the neighboring walls of the cell to the wall list.</li>
</ol></li>
</ul></li>
<li><ol start="2">
<li>Remove the wall from the list.</li>
</ol></li>
</ul></li>
</ol>
</blockquote>
<p>from
<a href="http://en.wikipedia.org/wiki/Maze_generation_algorithm" rel="noreferrer" title="this article on maze generationquot;">this article on maze generation.</a></p>
<p>How do I determine whether or not a cell is a valid candidate for the wall list? I would like to change my algorithm so that it produces a correct maze. Any ideas that would help me solve my problem would be appreciated.</p> | 29,758,926 | 8 | 3 | null | 2015-04-20 05:13:00.49 UTC | 8 | 2022-09-18 04:57:55.873 UTC | null | null | null | null | 3,295,845 | null | 1 | 16 | algorithm|graph-theory|maze|minimum-spanning-tree | 14,958 | <p>The description in the Wikipedia article truly deserves improvement.</p>
<p>The first confusing part of the article is, that the description of the randomized Prim's algorithm does not elaborate on the assumed data structure used by the algorithm. Thus, phrases like "opposite cell" become confusing.</p>
<p>Basically there are 2 main approaches "maze generator programmers" can opt for:</p>
<ol>
<li>Cells have walls or passages to their 4 neighbors. The information about walls/passages is stored and manipulated.</li>
<li>Cells can either be Blocked (walls) or Passages, without storing any extra connectivity information.</li>
</ol>
<p>Depending on which model (1) or (2) the reader has in mind when reading the description of the algorithm, they either understand or do not understand.</p>
<p>Me, personally I prefer to use cells as either walls or passages, rather than fiddling with dedicated passage/wall information.</p>
<p>Then, the "frontier" patches have a distance of 2 (rather than 1) from a passage. A random frontier patch from the list of frontier patches is selected and connected to a random neighboring passage (at distance 2) by means of also making the cell between frontier patch and neighboring passage a passage.</p>
<p>Here my F# implementation of how it looks like:</p>
<pre class="lang-ml prettyprint-override"><code>let rng = new System.Random()
type Cell = | Blocked | Passage
type Maze =
{
Grid : Cell[,]
Width : int
Height : int
}
let initMaze dx dy =
let six,siy = (1,1)
let eix,eiy = (dx-2,dy-2)
{
Grid = Array2D.init dx dy
(fun _ _ -> Blocked
)
Width = dx
Height = dy
}
let generate (maze : Maze) : Maze =
let isLegal (x,y) =
x>0 && x < maze.Width-1 && y>0 && y<maze.Height-1
let frontier (x,y) =
[x-2,y;x+2,y; x,y-2; x, y+2]
|> List.filter (fun (x,y) -> isLegal (x,y) && maze.Grid.[x,y] = Blocked)
let neighbor (x,y) =
[x-2,y;x+2,y; x,y-2; x, y+2]
|> List.filter (fun (x,y) -> isLegal (x,y) && maze.Grid.[x,y] = Passage)
let randomCell () = rng.Next(maze.Width),rng.Next(maze.Height)
let removeAt index (lst : (int * int) list) : (int * int) list =
let x,y = lst.[index]
lst |> List.filter (fun (a,b) -> not (a = x && b = y) )
let between p1 p2 =
let x =
match (fst p2 - fst p1) with
| 0 -> fst p1
| 2 -> 1 + fst p1
| -2 -> -1 + fst p1
| _ -> failwith "Invalid arguments for between()"
let y =
match (snd p2 - snd p1) with
| 0 -> snd p1
| 2 -> 1 + snd p1
| -2 -> -1 + snd p1
| _ -> failwith "Invalid arguments for between()"
(x,y)
let connectRandomNeighbor (x,y) =
let neighbors = neighbor (x,y)
let pickedIndex = rng.Next(neighbors.Length)
let xn,yn = neighbors.[pickedIndex]
let xb,yb = between (x,y) (xn,yn)
maze.Grid.[xb,yb] <- Passage
()
let rec extend front =
match front with
| [] -> ()
| _ ->
let pickedIndex = rng.Next(front.Length)
let xf,yf = front.[pickedIndex]
maze.Grid.[xf,yf] <- Passage
connectRandomNeighbor (xf,yf)
extend ((front |> removeAt pickedIndex) @ frontier (xf,yf))
let x,y = randomCell()
maze.Grid.[x,y] <- Passage
extend (frontier (x,y))
maze
let show maze =
printfn "%A" maze
maze.Grid |> Array2D.iteri
(fun y x cell ->
if x = 0 && y > 0 then
printfn "|"
let c =
match cell with
| Blocked -> "X"
| Passage -> " "
printf "%s" c
)
maze
let render maze =
let cellWidth = 10;
let cellHeight = 10;
let pw = maze.Width * cellWidth
let ph = maze.Height * cellHeight
let passageBrush = System.Drawing.Brushes.White
let wallBrush = System.Drawing.Brushes.Black
let bmp = new System.Drawing.Bitmap(pw,ph)
let g = System.Drawing.Graphics.FromImage(bmp);
maze.Grid
|> Array2D.iteri
(fun y x cell ->
let brush =
match cell with
| Passage -> passageBrush
| Blocked -> wallBrush
g.FillRectangle(brush,x*cellWidth,y*cellHeight,cellWidth,cellHeight)
)
g.Flush()
bmp.Save("""E:\temp\maze.bmp""")
initMaze 50 50 |> generate |> show |> render
</code></pre>
<p>A resulting maze then can look like this:</p>
<p><img src="https://i.stack.imgur.com/D5QgT.png" alt="enter image description here"></p>
<p>Here an attempt to describe my solution in wikipedia "algorithm" style:</p>
<blockquote>
<ol>
<li>A Grid consists of a 2 dimensional array of cells.</li>
<li>A Cell has 2 states: Blocked or Passage.</li>
<li>Start with a Grid full of Cells in state Blocked.</li>
<li>Pick a random Cell, set it to state Passage and Compute its frontier cells.
A frontier cell of a Cell is a cell with distance 2 in state Blocked and within the grid.</li>
<li>While the list of frontier cells is not empty:
<ol>
<li>Pick a random frontier cell from the list of frontier cells.</li>
<li>Let neighbors(frontierCell) = All cells in distance 2 in state Passage.
Pick a random neighbor and connect the frontier cell with the neighbor by setting the cell in-between to state Passage.
Compute the frontier cells of the chosen frontier cell and add them to the frontier list.
Remove the chosen frontier cell from the list of frontier cells.</li>
</ol></li>
</ol>
</blockquote> |
16,516,107 | How can I store HashMap<String, ArrayList<String>> inside a list? | <p>My hashmap stores the string as key and arraylist as the values. Now, I need to embed this into a list. That is, it will be of the following form:</p>
<pre><code>List<HashMap<String, ArrayList<String>>>
</code></pre>
<p>These are the declarations I have used:</p>
<pre><code>Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
ArrayList<String> arraylist = new ArrayList<String>();
map.put(key,arraylist);
List<String> list = new ArrayList<String>();
</code></pre>
<p>Can anyone help me which method and how to use in the list to proceed storing my map into it?</p> | 16,516,670 | 5 | 4 | null | 2013-05-13 06:35:54.367 UTC | 6 | 2017-06-14 08:59:50.193 UTC | 2013-05-13 06:49:39.917 UTC | null | 445,517 | null | 2,376,600 | null | 1 | 24 | java|list|hashmap|append | 163,997 | <p><strong>Always try to use interface reference in Collection</strong>, this adds more flexibility.<br>
What is the problem with the below code?<br></p>
<pre><code>List<Map<String,List<String>>> list = new ArrayList<Map<String,List<String>>>();//This is the final list you need
Map<String, List<String>> map1 = new HashMap<String, List<String>>();//This is one instance of the map you want to store in the above list.
List<String> arraylist1 = new ArrayList<String>();
arraylist1.add("Text1");//And so on..
map1.put("key1",arraylist1);
//And so on...
list.add(map1);//In this way you can add.
</code></pre>
<p>You can easily do it like the above.</p> |
16,431,163 | Concatenate two (or n) streams | <ul>
<li><p>2 streams:</p>
<p>Given readable <a href="http://nodejs.org/api/stream.html">streams</a> <code>stream1</code> and <code>stream2</code>, what's an idiomatic (concise) way to <strong>get a stream containing <code>stream1</code> and <code>stream2</code> concatenated</strong>?</p>
<p>I cannot do <code>stream1.pipe(outStream); stream2.pipe(outStream)</code>, because then the stream contents are jumbled together.</p></li>
<li><p><em>n</em> streams:</p>
<p>Given an <a href="http://nodejs.org/api/events.html">EventEmitter</a> that emits an indeterminate number of streams, e.g.</p>
<pre><code>eventEmitter.emit('stream', stream1)
eventEmitter.emit('stream', stream2)
eventEmitter.emit('stream', stream3)
...
eventEmitter.emit('end')
</code></pre>
<p>what's an idiomatic (concise) way to <strong>get a stream with all streams concatenated together</strong>?</p></li>
</ul> | 16,448,357 | 11 | 0 | null | 2013-05-08 01:21:54.387 UTC | 13 | 2022-07-04 19:09:59.82 UTC | null | null | null | null | 525,872 | null | 1 | 34 | node.js|stream|eventemitter | 25,468 | <p>The <a href="https://github.com/felixge/node-combined-stream" rel="noreferrer">combined-stream</a> package concatenates streams. Example from the README:</p>
<pre><code>var CombinedStream = require('combined-stream');
var fs = require('fs');
var combinedStream = CombinedStream.create();
combinedStream.append(fs.createReadStream('file1.txt'));
combinedStream.append(fs.createReadStream('file2.txt'));
combinedStream.pipe(fs.createWriteStream('combined.txt'));
</code></pre>
<p>I believe you have to append all streams at once. If the queue runs empty, the <code>combinedStream</code> automatically ends. See <a href="https://github.com/felixge/node-combined-stream/issues/5" rel="noreferrer">issue #5</a>.</p>
<p>The <a href="https://github.com/Floby/node-stream-stream" rel="noreferrer">stream-stream</a> library is an alternative that has an explicit <code>.end</code>, but it's much less popular and presumably not as well-tested. It uses the streams2 API of Node 0.10 (see <a href="https://github.com/Floby/node-stream-stream/issues/3" rel="noreferrer">this discussion</a>).</p> |
16,408,300 | What are the differences between local branch, local tracking branch, remote branch and remote tracking branch? | <p>I just started using Git and I got really confused between different branches. Can anyone help me to figure out what the following branch types are?</p>
<ul>
<li>local branches</li>
<li>local tracking branches</li>
<li>remote branches </li>
<li>remote tracking branches </li>
</ul>
<p>What is the difference between them? And how do they work with each other?</p>
<p>A quick demo code will be really helpful I guess.</p> | 16,408,515 | 4 | 0 | null | 2013-05-06 22:24:39.84 UTC | 126 | 2021-01-06 05:20:30.007 UTC | 2017-05-08 12:55:19.843 UTC | null | 452,775 | null | 1,361,407 | null | 1 | 195 | git|version-control|git-branch|git-remote | 115,859 | <p>A <strong>local branch</strong> is a branch that only you (the local user) can see. It exists only on your local machine.</p>
<pre><code>git branch myNewBranch # Create local branch named "myNewBranch"
</code></pre>
<p>A <strong>remote branch</strong> is a branch on a remote location (in most cases <code>origin</code>). You can push the newly created local branch <code>myNewBranch</code> to <code>origin</code>. Now other users can track it.</p>
<pre><code>git push -u origin myNewBranch # Pushes your newly created local branch "myNewBranch"
# to the remote "origin".
# So now a new branch named "myNewBranch" is
# created on the remote machine named "origin"
</code></pre>
<p>A <strong>remote tracking branch</strong> is a local copy of a remote branch. When <code>myNewBranch</code> is pushed to <code>origin</code> using the command above, a remote tracking branch named <code>origin/myNewBranch</code> is created on your machine. This remote tracking branch tracks the remote branch <code>myNewBranch</code> on <code>origin</code>. You can update your <strong>remote tracking branch</strong> to be in sync with the <strong>remote branch</strong> using <code>git fetch</code> or <code>git pull</code>.</p>
<pre><code>git pull origin myNewBranch # Pulls new commits from branch "myNewBranch"
# on remote "origin" into remote tracking
# branch on your machine "origin/myNewBranch".
# Here "origin/myNewBranch" is your copy of
# "myNewBranch" on "origin"
</code></pre>
<p>A <strong>local tracking branch</strong> is a <strong>local branch</strong> that is tracking another branch. This is so that you can push/pull commits to/from the other branch. Local tracking branches in most cases track a remote tracking branch. When you push a local branch to <code>origin</code> using the <code>git push</code> command with a <code>-u</code> option (as shown above), you set up the local branch <code>myNewBranch</code> to track the remote tracking branch <code>origin/myNewBranch</code>. This is needed to use <code>git push</code> and <code>git pull</code> without specifying an upstream to push to or pull from.</p>
<pre><code>git checkout myNewBranch # Switch to myNewBranch
git pull # Updates remote tracking branch "origin/myNewBranch"
# to be in sync with the remote branch "myNewBranch"
# on "origin".
# Pulls these new commits from "origin/myNewBranch"
# to local branch "myNewBranch which you just switched to.
</code></pre> |
55,310,682 | Should I wrap every prop with useCallback or useMemo, when to use this hooks? | <p>With react hooks now available should I in case of functional components wrap every function passed with props with <a href="https://reactjs.org/docs/hooks-reference.html#usecallback" rel="noreferrer">useCallback</a> and every other props value with <a href="https://reactjs.org/docs/hooks-reference.html#usememo" rel="noreferrer">useMemo</a>?</p>
<p>Also having custom function inside my component dependent on any props value should I wrap it with <a href="https://reactjs.org/docs/hooks-reference.html#usecallback" rel="noreferrer">useCallback</a>?</p>
<p>What are good practices to decide which props or const values from component wrap with this hooks ?</p>
<p><strong>If this improves performance why not to do it at all times ?</strong></p>
<p>Lets consider custom button where we wrap click handler and add custom logic</p>
<pre><code>function ExampleCustomButton({ onClick }) {
const handleClick = useCallback(
(event) => {
if (typeof onClick === 'function') {
onClick(event);
}
// do custom stuff
},
[onClick]
);
return <Button onClick={handleClick} />;
}
</code></pre>
<p>Lets consider custom button where we wrap click handler and add custom logic on condition</p>
<pre><code>function ExampleCustomButton({ someBool }) {
const handleClick = useCallback(
(event) => {
if (someBool) {
// do custom stuff
}
},
[someBool]
);
return <Button onClick={handleClick} />;
}
</code></pre>
<p>Should i in this two cases wrap my handler with <a href="https://reactjs.org/docs/hooks-reference.html#usecallback" rel="noreferrer">useCallback</a> ?</p>
<p>Similar case with use memo.</p>
<pre><code>function ExampleCustomButton({ someBool }) {
const memoizedSomeBool = useMemo(() => someBool, [someBool])
const handleClick = useCallback(
(event) => {
if (memoizedSomeBool) {
// do custom stuff
}
},
[memoizedSomeBool]
);
return <Button onClick={handleClick} />;
}
</code></pre>
<p>In this example I even pass memoized value to <a href="https://reactjs.org/docs/hooks-reference.html#usecallback" rel="noreferrer">useCallback</a>. </p>
<p>Another case what if in the component tree many components memoize same value ? How does this impact performance ?</p> | 55,371,823 | 3 | 6 | null | 2019-03-23 04:45:31.7 UTC | 14 | 2022-04-28 20:16:43.657 UTC | 2022-04-28 20:16:43.657 UTC | null | 1,218,980 | null | 2,160,958 | null | 1 | 38 | javascript|reactjs|react-hooks | 21,507 | <p>Not worth it, for multiple reasons:</p>
<ol>
<li>Even official docs say you should do it only when necessary.</li>
<li>Keep in mind that <em>premature optimization is the root of all evil</em> :)</li>
<li>It makes DX (developer experience) far worse: it's harder to read; harder to write; harder to refactor. </li>
<li>When dealing with primitives (like in your example) memoizing costs more CPU power than not doing it. A primitive value doesn't have a concept of <em>references</em>, so there's nothing to memoize in them. On the other hand, memoization itself (as any other hook) <strong>does</strong> require some tiny processing, nothing is for free. Even though it's tiny, it's still more than nothing (compared to just passing a primitive through), so you'd shoot your own foot with this approach.</li>
</ol>
<p>To put all together - you'd waste more time typing all the hooks than a user would gain on having them in the application if you want to put them everywhere. The good old rule applies: <strong>Measure, then optimize</strong>.</p> |
15,113,030 | Center align a div horizontally using default Twitter Bootstrap CSS | <p>I know how to center align a div horizontally in CSS. You need to make the width to something less than 100% and have auto margin on both left and right sides. I want to do this default styles of Twitter Bootstrap. I don't want to write additional CSS. Wondering whether it's possible to achieve using default style used in Twitter Bootstrap.</p>
<p>To set width of the div, I am using <code>span*</code>. But <code>span*</code> is <code>float: left</code>. Is there any class, which can set the width of the div, but will not add <code>float: left</code>?</p> | 15,113,314 | 5 | 3 | null | 2013-02-27 13:14:34.597 UTC | 1 | 2015-01-14 08:50:50.11 UTC | null | null | null | null | 225,790 | null | 1 | 6 | css|twitter-bootstrap | 42,695 | <p>To horizontally align a div that is using an even span styles (span2, span4, etc...), you need to use offset.</p>
<pre><code><div class="offset3 span6">
...
</div>
</code></pre> |
17,294,809 | Reading a line using scanf() not good? | <pre><code>scanf(" %[^\n]",line);
</code></pre>
<p>A friend of mine suggested that using <code>fgets()</code> to read a line as input would be a much better idea than using <code>scanf()</code> as in the statement above. Is he justified?</p> | 17,294,869 | 8 | 5 | null | 2013-06-25 10:22:29.687 UTC | 9 | 2020-03-03 00:03:11.413 UTC | 2013-08-22 01:05:35.027 UTC | null | 1,009,479 | null | 1,656,150 | null | 1 | 22 | c|scanf|stdio | 70,654 | <p><a href="http://www.cplusplus.com/reference/cstdio/fgets/"><code>char * fgets ( char * str, int num, FILE * stream );</code></a> is safe to use because it avoid <a href="http://en.wikipedia.org/wiki/Buffer_overflow">buffer overflow</a> problem, it scans only <code>num-1</code> number of char.</p>
<blockquote>
<p>Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.</p>
</blockquote>
<p>here second argument <code>num</code> is Maximum number of characters to be copied into str (including the terminating null-character).</p>
<p>For example suppose in your code a string array capacity is just <code>5</code> chars long as below. </p>
<pre><code> char str[5];
fgets (str, 5, fp); //5 =you have provision to avoid buffer overrun
</code></pre>
<p>Using above code, if input from <code>fp</code> is longer then <code>4</code> chars, <code>fgets()</code> will read just first <code>4</code> chars then appends <code>\0</code> (<em>, and discard other extra input chars, just stores five char in <code>str[]</code></em>). </p>
<p>Whereas <code>scanf(" %[^\n]",str);</code> will read until <code>\n</code> not found and if input string is longer then <code>4</code> chars <code>scanf()</code> will cause of <a href="http://en.wikipedia.org/wiki/Buffer_overflow">buffer overflow</a> (as <code>scanf</code> will try to access memory beyond max index <code>4</code> in <code>str[]</code>). </p> |
17,438,857 | How to format date with hours, minutes and seconds when using jQuery UI Datepicker? | <p>Is it possible to format a date with <a href="http://jqueryui.com/datepicker/" rel="noreferrer">jQuery UI Datepicker</a> as to show hours, minutes and seconds?</p>
<p>This is my current mockup:</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() {
$('#datepicker').datepicker({ dateFormat: 'yyy-dd-mm HH:MM:ss' }).val();
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<title>snippet</title>
</head>
<body>
<input type="text" id="datepicker">
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script></code></pre>
</div>
</div>
</p>
<p>When I call <code>.datepicker({ dateFormat: 'yyy-dd-mm HH:MM:ss' })</code> the returned value is:</p>
<blockquote>
<p>201313-07-03 HH:July:ss</p>
</blockquote>
<p>Here is a <a href="http://jsfiddle.net/Qv36W/1/" rel="noreferrer">JSFiddle</a>.</p> | 17,438,931 | 10 | 2 | null | 2013-07-03 02:44:09.387 UTC | 7 | 2020-11-03 11:47:18.457 UTC | 2017-11-15 12:00:57.437 UTC | null | 3,931,192 | null | 2,496,567 | null | 1 | 58 | javascript|jquery|datepicker|jquery-ui-datepicker | 330,512 | <pre><code>$("#datepicker").datepicker("option", "dateFormat", "yy-mm-dd ");
</code></pre>
<p>For the time picker, you should add timepicker to Datepicker, and it would be formatted with one equivalent command.</p>
<p><strong>EDIT</strong></p>
<p>Use this one that extend jQuery UI Datepicker. You can pick up both date and time.</p>
<p><a href="http://trentrichardson.com/examples/timepicker/">http://trentrichardson.com/examples/timepicker/</a></p> |
17,429,040 | Creating user with encrypted password in PostgreSQL | <p>Is it possible to create a user in PostgreSQL without providing the plain text password (ideally, I would like to be able to create a user providing only its password crypted with sha-256) ?</p>
<p>What I would like to do is to create a user with something like that :</p>
<pre><code>CREATE USER "martin" WITH PASSWORD '$6$kH3l2bj8iT$KKrTAKDF4OoE7w.oy(...)BPwcTBN/V42hqE.';
</code></pre>
<p>Is there some way to do that ?</p>
<p>Thank you for your help.</p> | 17,431,573 | 4 | 0 | null | 2013-07-02 15:02:22.597 UTC | 20 | 2021-10-07 11:17:22.153 UTC | null | null | null | null | 2,466,911 | null | 1 | 61 | postgresql|passwords|sha|plaintext | 101,147 | <p>You may provide the password already hashed with <code>md5</code>, as said in the doc (<a href="http://www.postgresql.org/docs/9.2/static/sql-createrole.html">CREATE ROLE</a>):</p>
<blockquote>
<p>ENCRYPTED UNENCRYPTED These key words control whether the password is
stored encrypted in the system catalogs. (If neither is specified, the
default behavior is determined by the configuration parameter
password_encryption.) <strong>If the presented password string is already in
MD5-encrypted format, then it is stored encrypted as-is</strong>, regardless of
whether ENCRYPTED or UNENCRYPTED is specified (since the system cannot
decrypt the specified encrypted password string). This allows
reloading of encrypted passwords during dump/restore.</p>
</blockquote>
<p>The information that's missing here is that the MD5-encrypted string should be the password concatened with the username, plus <code>md5</code> at the beginning.</p>
<p>So for example to create <code>u0</code> with the password <code>foobar</code>, knowing that <code>md5('foobaru0')</code> is <code>ac4bbe016b808c3c0b816981f240dcae</code>:</p>
<pre><code>CREATE USER u0 PASSWORD 'md5ac4bbe016b808c3c0b816981f240dcae';
</code></pre>
<p>and then u0 will be able to log in by typing <code>foobar</code> as the password.</p>
<p>I don't think that there's currently a way to use <code>SHA-256</code> instead of <code>md5</code> for PostgreSQL passwords.</p> |
17,604,232 | Edit a commit message in SourceTree Windows (already pushed to remote) | <p>How do I edit an incorrect commit message in SourceTree without touching the command line?</p>
<p><strong>Additional details:</strong></p>
<ul>
<li>This is not the latest commit.</li>
<li>Everything was already pushed to Bitbucket.</li>
<li>This is a private repository and I am the only collaborator.</li>
<li>I don't mind losing any of the previous commits, as I can re-commit them anytime.</li>
<li>I don't want however to lose any code modification ever made.</li>
</ul>
<p><strong>Outcome:</strong></p>
<ul>
<li>As it seems impossible at the moment according to your comments and replies, I'm going to create a new repository and start all over. Thanks all for your help!</li>
</ul> | 23,239,109 | 4 | 0 | null | 2013-07-11 21:57:59.31 UTC | 114 | 2020-02-06 10:58:24.513 UTC | 2016-07-01 17:55:36.75 UTC | null | 102,937 | null | 2,327,283 | null | 1 | 251 | git|atlassian-sourcetree | 218,795 | <p>Here are the steps to edit the commit message of a previous commit (<strong><em>which is
not the most recent commit</em></strong>) using <strong>SourceTree for Windows version 1.5.2.0</strong>:</p>
<h2>Step 1</h2>
<p>Select the commit <strong><em>immediately before</em></strong> the commit that you want to edit.
For example, if I want to edit the commit with message "FOOBAR!" then I need
to select the commit that comes right before it:</p>
<p><img src="https://i.stack.imgur.com/IoAzf.png" alt="Selecting commit before the one that I want to edit."></p>
<h2>Step 2</h2>
<p>Right-click on the selected commit and click <code>Rebase children...interactively</code>:</p>
<p><img src="https://i.stack.imgur.com/Vx6z1.png" alt="Selecting "Rebase children interactively"."></p>
<h2>Step 3</h2>
<p>Select the commit that you want to edit, then click <code>Edit Message</code> at the
bottom. In this case, I'm selecting the commit with the message "FOOBAR!":</p>
<p><img src="https://i.stack.imgur.com/MzfC5.png" alt="Select the commit that you want to edit."></p>
<h2>Step 4</h2>
<p>Edit the commit message, and then click <code>OK</code>. In my example, I've added
"SHAZBOT! SKADOOSH!"</p>
<p><img src="https://i.stack.imgur.com/PRUeA.png" alt="Edit the commit message"></p>
<h2>Step 5</h2>
<p>When you return to interactive rebase window, click on <code>OK</code> to finish the
rebase:</p>
<p><img src="https://i.stack.imgur.com/1knk8.png" alt="Click OK to finish."></p>
<h2>Step 6</h2>
<p>At this point, you'll need to force-push your new changes since you've rebased
commits that you've already pushed. However, the current 1.5.2.0 version of
SourceTree for Windows does not allow you to force-push through the GUI, so
you'll need to use Git from the command line anyways in order to do that.</p>
<p>Click <code>Terminal</code> from the GUI to open up a terminal.</p>
<p><img src="https://i.stack.imgur.com/iUYEa.png" alt="Click Terminal"></p>
<h2>Step 7</h2>
<p>From the terminal force-push with the following command,</p>
<pre><code>git push origin <branch> -f
</code></pre>
<p>where <code><branch></code> is the name of the branch that you want to push, and <code>-f</code> means
to force the push. The force push <strong><em>will overwrite</em></strong> your commits on your
remote repo, but that's OK in your case since you said that you're not sharing
your repo with other people.</p>
<p><strong>That's it! You're done!</strong></p> |
18,514,504 | how to call a function from another function in Jquery | <pre><code><script>
$(document).ready(function(){
//Load City by State
$('#billing_state_id').live('change', function() {
//do something
});
$('#click_me').live('click', function() {
//do something
//need to recall $('#billing_state_id').live('change', function() { but how?
});
});
</script>
</code></pre>
<p>Load City by State working fine but i don't know whether it's possible or not to call it within another function like <code>$('#click_me').live('click', function()</code>.</p> | 18,514,561 | 3 | 4 | null | 2013-08-29 15:02:37.543 UTC | 2 | 2015-11-08 13:35:32.79 UTC | 2013-08-29 15:03:39.433 UTC | null | 2,266,713 | null | 1,911,703 | null | 1 | 15 | jquery|function | 113,301 | <p>I assume you don't want to rebind the event, but call the handler.</p>
<p>You can use <code>trigger()</code> to trigger events:</p>
<pre><code>$('#billing_state_id').trigger('change');
</code></pre>
<p>If your handler doesn't rely on the event context and you don't want to trigger other handlers for the event, you could also name the function:</p>
<pre><code>function someFunction() {
//do stuff
}
$(document).ready(function(){
//Load City by State
$('#billing_state_id').live('change', someFunction);
$('#click_me').live('click', function() {
//do something
someFunction();
});
});
</code></pre>
<p>Also note that <code>live()</code> is deprecated, <code>on()</code> is the new hotness.</p> |
5,414,496 | Using WebGL Shader Language (GLSL) for arbitrary vector mathematics in JavaScript | <p>The WebGL Shader Language (GLSL) is a very powerful tool for multidimensional vector mathematics. </p>
<p>Is there any possibility to use that power from JavaScript (running in web browser) for private non-3D calculations? Getting data in is possible, but is there any way to get data out to JavaScript after shader calculations are done?</p>
<p>No actual drawing is necessary, only calculating vectors.
(I am toying with an idea of hardware accelerated gravity simulator written in JavaScript.)</p>
<p>Thank You!</p>
<hr>
<p>In the news: Khronos seems to be developing <a href="https://www.khronos.org/webcl" rel="nofollow noreferrer">WebCL</a> which will be a JavaScript accessible version of <a href="http://en.wikipedia.org/wiki/OpenCL" rel="nofollow noreferrer">OpenCL</a>. That is exactly what I am looking for, but it will take some time...</p> | 5,419,887 | 3 | 0 | null | 2011-03-24 03:42:03.743 UTC | 21 | 2018-04-05 12:30:29.173 UTC | 2018-04-05 12:30:29.173 UTC | null | -1 | null | 674,253 | null | 1 | 29 | javascript|math|matrix|glsl|webgl | 7,160 | <p>As far as I can see from the <a href="http://www.khronos.org/registry/webgl/specs/latest/">spec</a> WebGL supports framebuffer objects and read-back operations. This is sufficient for you to transform the data and get it back into client space. Here is a sequence of operations:</p>
<ol>
<li>Create FBO with attachment render buffers that you need to store the result; bind it</li>
<li>Upload all input data into textures (the same size).</li>
<li>Create the GLSL processing shader that will do the calculus inside the fragment part, reading the input from textures and writing the output into destination renderbuffers; bind it</li>
<li>Draw a quad; read back the render buffers via <code>glReadPixels</code>.</li>
</ol> |
5,307,656 | How do I convert a binary string to hex using C? | <p>How do I convert an 8-bit binary string (e.g. "10010011") to hexadecimal using C?</p> | 5,307,692 | 4 | 2 | null | 2011-03-15 04:53:12.587 UTC | null | 2011-03-15 09:55:22.403 UTC | 2011-03-15 09:55:22.403 UTC | null | 118 | null | 659,962 | null | 1 | 4 | c|binary|hex | 38,882 | <p>Something like that:</p>
<pre><code>char *bin="10010011";
char *a = bin;
int num = 0;
do {
int b = *a=='1'?1:0;
num = (num<<1)|b;
a++;
} while (*a);
printf("%X\n", num);
</code></pre> |
5,347,341 | How to align center the title or label in activity? | <p>I know there are two ways of setting the title of activity. One way is the setting it in the android manifest like this <strong>android:label="@string/app_name"</strong>. Second is programmatically setting in activity class like <strong>setTitle("Hello World!")</strong>. Both ways are positioned in the left side but how can I put it in the center?</p> | 5,347,391 | 4 | 0 | null | 2011-03-18 02:18:45.397 UTC | 6 | 2018-08-17 14:59:41.19 UTC | null | null | null | null | 504,470 | null | 1 | 7 | android|android-activity|label|title | 50,985 | <p>You will need to define a custom title style/theme. Look in the samples for com.example.android.apis.app.CustomTitle.</p> |
23,251,759 | How to determine what is the probability distribution function from a numpy array? | <p>I have searched around and to my surprise it seems that this question has not been answered.</p>
<p>I have a Numpy array containing 10000 values from measurements. I have plotted a histogram with Matplotlib, and by visual inspection the values seem to be normally distributed:</p>
<p><img src="https://i.stack.imgur.com/rococ.png" alt="Histogram"></p>
<p>However, I would like to validate this. I have found a normality test implemented under <a href="http://docs.scipy.org/doc/scipy-0.13.0/reference/generated/scipy.stats.mstats.normaltest.html" rel="noreferrer">scipy.stats.mstats.normaltest</a>, but the result says otherwise. I get this output:</p>
<pre><code>(masked_array(data = [1472.8855375088663],
mask = [False],
fill_value = 1e+20)
, masked_array(data = [ 0.],
mask = False,
fill_value = 1e+20)
</code></pre>
<p>)</p>
<p>which means that the chances that the dataset is normally distributed are 0. I have re-run the experiments and tested them again obtaining the same outcome, and in the "best" case the p value was 3.0e-290.</p>
<p>I have tested the function with the following code and it seems to do what I want:</p>
<pre><code>import numpy
import scipy.stats as stats
mu, sigma = 0, 0.1
s = numpy.random.normal(mu, sigma, 10000)
print stats.normaltest(s)
(1.0491016699730547, 0.59182113002186942)
</code></pre>
<p>If I have understood and used the function correctly it means that the values are not normally distributed. (And honestly I have no idea why there is a difference in the output, i.e. less details.)</p>
<p>I was pretty sure that it is a normal distribution (although my knowledge of statistics is basic), and I don't know what could the alternative be. How can I check what is the probability distribution function in question? </p>
<p><strong>EDIT:</strong></p>
<p>My Numpy array containing 10000 values is generated like this (I know that's not the best way to populate a Numpy array), and afterwards the normaltest is run:</p>
<pre><code>values = numpy.empty(shape=10000, 1))
for i in range(0, 10000):
values[i] = measurement(...) # The function returns a float
print normaltest(values)
</code></pre>
<p><strong>EDIT 2:</strong></p>
<p>I have just realised that the discrepancy between the outputs is because I have inadvertently used two different functions (scipy.stats.normaltest() and scipy.stats.mstats.normaltest()), but it does not make a difference since the relevant part of the output is the same regardless of the used function.</p>
<p><strong>EDIT 3:</strong></p>
<p>Fitting the histogram with the suggestion from askewchan:</p>
<pre><code>plt.plot(bin_edges, scipy.stats.norm.pdf(bin_edges, loc=values.mean(), scale=values.std()))
</code></pre>
<p>results in this:</p>
<p><img src="https://i.stack.imgur.com/aHpC6.png" alt="Fitted histogram"></p>
<p><strong>EDIT 4:</strong></p>
<p>Fitting the histogram with the suggestion from user user333700:</p>
<pre><code>scipy.stats.t.fit(data)
</code></pre>
<p>results in this:</p>
<p><img src="https://i.stack.imgur.com/c9QX8.png" alt="enter image description here"></p> | 23,252,488 | 2 | 11 | null | 2014-04-23 17:53:19.113 UTC | 10 | 2020-05-01 16:47:20.223 UTC | 2014-04-24 07:04:45.517 UTC | null | 3,565,679 | null | 3,565,679 | null | 1 | 23 | python|math|numpy|statistics|scipy | 18,776 | <p>Assuming you have used the test correctly, my guess is that you have a <strong>small</strong> deviation from a normal distribution and because your sample size is so large, even small deviations will lead to a rejection of the null hypothesis of a normal distribution.</p>
<p>One possibility is to visually inspect your data by plotting a <code>normed</code> histogram with a large number of bins and the pdf with <code>loc=data.mean()</code> and <code>scale=data.std()</code>. </p>
<p>There are alternative test for testing normality, statsmodels has Anderson-Darling and Lillifors (Kolmogorov-Smirnov) tests when the distribution parameters are estimated.</p>
<p>However, I expect that the results will not differ much given the large sample size.</p>
<p>The main question is whether you want to test whether your sample comes "exactly" from a normal distribution, or whether you are just interested in whether your sample comes from a distribution that is very close to the normal distribution, <strong>close</strong> in terms of practical usage.</p>
<p>To elaborate on the last point:</p>
<p><a href="http://jpktd.blogspot.ca/2012/10/tost-statistically-significant.html" rel="nofollow">http://jpktd.blogspot.ca/2012/10/tost-statistically-significant.html</a>
<a href="http://www.graphpad.com/guides/prism/6/statistics/index.htm?testing_for_equivalence2.htm" rel="nofollow">http://www.graphpad.com/guides/prism/6/statistics/index.htm?testing_for_equivalence2.htm</a></p>
<p>As the sample size increases a hypothesis test gains more power, that means that the test will be able to reject the null hypothesis of equality even for smaller and smaller differences. If we keep our significance level fixed, then eventually we will reject tiny differences that we don't really care about.</p>
<p>An alternative type of hypothesis test is where we want to show that our sample is close to the given point hypothesis, for example two samples have almost the same mean. The problem is that we have to define what our equivalence region is.</p>
<p>In the case of goodness of fit tests we need to choose a distance measure and define a threshold for the distance measure between the sample and the hypothesized distribution. I have not found any explanation where intuition would help to choose this distance threshold.</p>
<p>stats.normaltest is based on deviations of skew and kurtosis from those of the normal distribution. </p>
<p>Anderson-Darling is based on a integral of the weighted squared differences between the cdf.</p>
<p>Kolmogorov-Smirnov is based on the maximum absolute difference between the cdf.</p>
<p>chisquare for binned data would be based on the weighted sum of squared bin probabilities.</p>
<p>and so on.</p>
<p>I only ever tried equivalence testing with binned or discretized data, where I used a threshold from some reference cases which was still rather arbitrary.</p>
<p>In medical equivalence testing there are some predefined standards to specify when two treatments can be considered as equivalent, or similarly as inferior or superior in the one sided version.</p> |
15,382,422 | Text doesn't start from the left top of input text field | <p>I have an input field with a fixed height. The text is vertically centered, but I want it at the top left of the input.</p>
<p>CSS</p>
<pre><code>.wideInput{
text-align: left;
padding: 0.4em;
width: 400px;
height: 200px;
}
</code></pre>
<p>HTML</p>
<pre><code><input class="longInput" value="<?php echo $row['foodPrice']; ?>" />
</code></pre>
<p>Here's a jsFiddle that demonstrates the problem > <a href="http://jsfiddle.net/9cR5j/">http://jsfiddle.net/9cR5j/</a></p> | 15,382,459 | 6 | 0 | null | 2013-03-13 10:16:23.653 UTC | 2 | 2020-06-14 08:44:51.743 UTC | 2014-10-06 17:47:31.99 UTC | null | 1,828,051 | null | 2,038,257 | null | 1 | 18 | html|css | 57,115 | <p>if what that than remove <code>padding: 0.4em;</code> and set </p>
<pre><code>padding-left:0;
padding-top:0;
padding-bottom:0.4em;
padding-right: 0.4em;
</code></pre>
<p>After doing change change class name here </p>
<pre><code><input class="wideInput" value="<?php echo $row['foodPrice']; ?>" />
</code></pre>
<p>instead of <code>longInput</code> it will be <code>wideInput</code></p>
<hr>
<p>Update</p>
<p><a href="http://jsfiddle.net/9cR5j/2/" rel="nofollow"><strong>JsFiddle demo with TextArea</strong></a></p>
<p>this will work with textarea only because input is just allow to enter value in one line i.e no enter keyallowed or it doent wrap long text , it just add data in one line </p> |
15,337,777 | Fit a line with LOESS in R | <p>I have a data set with some points in it and want to fit a line on it. I tried it with the <code>loess</code> function. Unfortunately I get very strange results. See the plot bellow. I expect a line that goes more through the points and over the whole plot. How can I achieve that?
<img src="https://i.stack.imgur.com/Rtwtg.png" alt="plot"></p>
<p>How to reproduce it: </p>
<p>Download the dataset from <a href="https://www.dropbox.com/s/ud32tbptyvjsnp4/data.R?dl=1" rel="noreferrer">https://www.dropbox.com/s/ud32tbptyvjsnp4/data.R?dl=1</a> (only two kb) and use this code:</p>
<pre><code>load(url('https://www.dropbox.com/s/ud32tbptyvjsnp4/data.R?dl=1'))
lw1 = loess(y ~ x,data=data)
plot(y ~ x, data=data,pch=19,cex=0.1)
lines(data$y,lw1$fitted,col="blue",lwd=3)
</code></pre>
<p>Any help is greatly appreciated. Thanks!</p> | 15,337,778 | 3 | 1 | null | 2013-03-11 09:39:50.873 UTC | 8 | 2018-11-14 16:17:18.117 UTC | 2017-05-18 07:22:06.347 UTC | null | 55,070 | leo | 55,070 | null | 1 | 23 | r|loess | 62,055 | <p>You've plotted fitted values against <code>y</code> instead of against <code>x</code>. Also, you will need to order the x values before plotting a line. Try this:</p>
<pre><code>lw1 <- loess(y ~ x,data=data)
plot(y ~ x, data=data,pch=19,cex=0.1)
j <- order(data$x)
lines(data$x[j],lw1$fitted[j],col="red",lwd=3)
</code></pre>
<p><img src="https://i.stack.imgur.com/mum5U.png" alt="enter image description here"></p> |
28,204,978 | Facebook RSS feeds have stopped working | <p>We are showing feeds from Facebook on our website. Until yesterday, we were able to retrieve the feeds in JSON format using the URL below:</p>
<pre><code>https://www.facebook.com/feeds/page.php?format=json&id=[id_of_the_page]
</code></pre>
<p>But today I found that the link was broken. Is there a reason for it breaking?</p>
<p>And is there a way that I can access the JSON feed for my page using the new Graph API?</p> | 28,291,957 | 2 | 4 | null | 2015-01-29 00:23:01.943 UTC | 11 | 2015-02-23 07:59:44.103 UTC | 2015-02-23 07:59:44.103 UTC | null | 3,001,761 | null | 2,789,978 | null | 1 | 24 | facebook | 22,024 | <p>Finally I was able to get the Facebook page feeds back on my website. Here goes the steps I followed to restore the feeds:</p>
<p>Step 1: I logged into Facebook developer portal and created new Facebook Application (Website). You can find the details on how create a Facebook App from the following link: <a href="https://developers.facebook.com/docs/web/tutorials/scrumptious/register-facebook-application">How to Create Facebook App</a> </p>
<p>On the newly created app you will find the "App ID" and "App Secret" values.</p>
<p>Step 2: On my website, I used the "App ID" and "App Secret" to retrieve an "access_token" from Facebook. I used C#, so the line of code I used was:</p>
<pre><code>string access_token = "";
try {
access_token = webClient.DownloadString("https://graph.facebook.com/oauth/access_token?client_id=616255239999&client_secret=989898989898acec7c3aabbccddf84b66&grant_type=client_credentials");
}
catch {}
</code></pre>
<p>Replace client id with app id and client secret with app secret values copied from the previous step. If the values are correct you will get a response like:</p>
<pre><code>access_token=616255878567492343|UYgAYWXYztpFGRawnZ2VlTE
</code></pre>
<p>Step 3: Now use the access token retrieved from the previous stage to call Facebook Graph API to get the feeds:</p>
<pre><code>string facebookjson = webClient.DownloadString("https://graph.facebook.com/v2.2/1730999949494/feed?access_token=616255878567492343|UYgAYWXYztpFGRawnZ2VlTE");
</code></pre>
<p>The construct of the URL would like below:</p>
<p><a href="https://graph.facebook.com/v2.2/[your_facebook_page_id]/feed?access_token=[your_access_token_value]">https://graph.facebook.com/v2.2/[your_facebook_page_id]/feed?access_token=[your_access_token_value]</a></p>
<p>And voila!! You get the feeds from your Facebook page in a JSON response. </p> |
9,210,765 | Any way to start Google Chrome in headless mode? | <p>I carefully revised the list of switches at <a href="http://peter.sh/experiments/chromium-command-line-switches/#chrome-frame" rel="noreferrer">http://peter.sh/experiments/chromium-command-line-switches/#chrome-frame</a> and I couldn't find anything that would launch Chrome in a hidden background process.</p>
<p>The closest I was able to is <code>--keep-alive-for-test</code> + custom packaged app, but the app fails to execute any passed code because (the way it reports) "no window - ChromeHidden".</p> | 34,170,686 | 11 | 7 | null | 2012-02-09 12:22:59.587 UTC | 29 | 2021-09-12 17:44:20.453 UTC | null | null | null | null | 608,886 | null | 1 | 62 | google-chrome|headless | 82,438 | <p><strong>TL;DR</strong></p>
<pre><code>google-chrome --headless --remote-debugging-port=9222 http://example.com
</code></pre>
<p>You'd also need <code>--disable-gpu</code> temporarily.</p>
<hr>
<p><strong>Tutorial</strong>:</p>
<p><a href="https://developers.google.com/web/updates/2017/04/headless-chrome" rel="noreferrer">https://developers.google.com/web/updates/2017/04/headless-chrome</a></p>
<hr>
<p>There's a work in progress: <a href="https://code.google.com/p/chromium/issues/detail?id=546953" rel="noreferrer">https://code.google.com/p/chromium/issues/detail?id=546953</a></p>
<blockquote>
<p>The main deliverables are:</p>
<ol>
<li>A library which headless applications can link to to.</li>
<li>A sample application which demonstrates the use of headless APIs.</li>
</ol>
</blockquote>
<p>So it would be possible to create a simple application that runs in console without connecting to display.</p>
<p><strong>Update Apr 18 '16:</strong> The work is mainly done. There's a public forum now:</p>
<p><a href="https://groups.google.com/a/chromium.org/forum/#!forum/headless-dev" rel="noreferrer">https://groups.google.com/a/chromium.org/forum/#!forum/headless-dev</a></p>
<p>Documentation is being in progress:</p>
<p><a href="https://chromium.googlesource.com/chromium/src/+/master/headless/README.md" rel="noreferrer">https://chromium.googlesource.com/chromium/src/+/master/headless/README.md</a></p>
<p><strong>Update Sep 20 '16:</strong> It looks like chrome will eventually get the "--headless" parameter:
<a href="https://bugs.chromium.org/p/chromium/issues/detail?id=612904" rel="noreferrer">https://bugs.chromium.org/p/chromium/issues/detail?id=612904</a></p>
<p>There was <a href="https://docs.google.com/presentation/d/1gqK9F4lGAY3TZudAtdcxzMQNEE7PcuQrGu83No3l0lw/edit?usp=sharing" rel="noreferrer">a presentation</a> on BlinkOn 6 (June 16/17, 2016)</p>
<p><strong>Update Nov 29 '16:</strong> Design doc for <code>--headless</code> flag: <a href="https://docs.google.com/document/d/1aIJUzQr3eougZQp90bp4mqGr5gY6hdUice8UPa-Ys90/edit#heading=h.qxqfzv2lj12s" rel="noreferrer">https://docs.google.com/document/d/1aIJUzQr3eougZQp90bp4mqGr5gY6hdUice8UPa-Ys90/edit#heading=h.qxqfzv2lj12s</a></p>
<p><strong>Update Dec 13 '16:</strong> <code>--headless</code> flag is expected to be available in Canary builds soon</p>
<p><strong>Update Mar 12 '17:</strong> Chrome 57 has a <code>--headless</code> flag working. Waiting for Selenium and other tools to catch up. User guide: <a href="https://chromium.googlesource.com/chromium/src/+/lkgr/headless/README.md" rel="noreferrer">https://chromium.googlesource.com/chromium/src/+/lkgr/headless/README.md</a></p> |
4,892,452 | RegEx Match multiple times in string | <p>I'm trying to extract values from a string which are between << and >>. But they could happen multiple times.</p>
<p>Can anyone help with the regular expression to match these;</p>
<pre><code>this is a test for <<bob>> who like <<books>>
test 2 <<frank>> likes nothing
test 3 <<what>> <<on>> <<earth>> <<this>> <<is>> <<too>> <<much>>.
</code></pre>
<p>I then want to foreach the GroupCollection to get all the values.</p>
<p>Any help greatly received.
Thanks.</p> | 4,892,517 | 4 | 0 | null | 2011-02-03 22:24:51.387 UTC | 7 | 2019-05-06 08:26:05.78 UTC | null | null | null | null | 228,861 | null | 1 | 28 | c#|regex | 52,551 | <p>Use a positive look ahead and look behind assertion to match the angle brackets, use <code>.*?</code> to match the shortest possible sequence of characters between those brackets. Find all values by iterating the <code>MatchCollection</code> returned by the <code>Matches()</code> method.</p>
<pre><code>Regex regex = new Regex("(?<=<<).*?(?=>>)");
foreach (Match match in regex.Matches(
"this is a test for <<bob>> who like <<books>>"))
{
Console.WriteLine(match.Value);
}
</code></pre>
<p><a href="https://dotnetfiddle.net/3QRzfh" rel="noreferrer">LiveDemo in DotNetFiddle</a></p> |
4,899,518 | Looking for a Simple Spring security example | <p>I am new to spring-security (Java) and I am looking for a good and <strong>simple</strong> example of: </p>
<ol>
<li><p>How to use spring security for login and logout</p></li>
<li><p>Make sure that the session exists on every page and if not redirect to the login again</p></li>
<li><p>How get access to the current User Session</p></li>
</ol>
<p>My project is currently working with spring MVC, and hibernate.<br>
I have built the loginAPI + loginDAO, I need now to combine the security and make some of the pages secured.</p>
<p>I searched for tutorials, but a lot of them are very complicated.</p> | 4,908,942 | 5 | 1 | null | 2011-02-04 15:09:26.213 UTC | 20 | 2017-06-26 01:24:38.767 UTC | 2017-05-26 02:58:08.42 UTC | null | 1,697,099 | null | 603,361 | null | 1 | 20 | spring|spring-mvc|spring-security | 47,432 | <p>Well.
This is I think by far is the best i have seen so far!<br>
<a href="http://krams915.blogspot.com/2010/12/spring-security-mvc-integration_18.html" rel="noreferrer">http://krams915.blogspot.com/2010/12/spring-security-mvc-integration_18.html</a></p> |
5,179,517 | How can I export an Adobe Connect recording as a video? | <p>I have links to recorded conferences, how can I export video from them?</p> | 13,575,393 | 5 | 0 | null | 2011-03-03 10:32:15.297 UTC | 24 | 2021-12-10 05:55:07.267 UTC | 2019-02-10 09:48:03.103 UTC | null | 395,857 | null | 471,149 | null | 1 | 40 | adobe|video-streaming|video-capture|conference | 79,562 | <ol>
<li>Log into your Adobe Connect account </li>
<li>Click on <em>Meetings > <strong>My Meetings</em></strong></li>
<li>Click on the link for the recording</li>
<li>Click the β<strong>Recordings</strong>β link (right-side of screen) </li>
<li>Click the link in the β<em>Name</em>β column </li>
<li>Copy the β<em>URL for Viewing</em>β β Example, <a href="http://mycompany.adobeconnect.com/p12345678/" rel="noreferrer">http://mycompany.adobeconnect.com/p12345678/</a></li>
<li>Paste it into a new browser tab then add the following to the end of the URL: <code>output/filename.zip?download=zip</code></li>
<li>Your URL should look similar to this example, <a href="http://mycompany.adobeconnect.com/p12345678/output/filename.zip?download=zip" rel="noreferrer">http://mycompany.adobeconnect.com/p12345678/output/filename.zip?download=zip</a></li>
</ol> |
4,903,060 | How to open file in Emacs via eshell? | <p>When in eshell is there a command for opening a file in another buffer?</p> | 4,903,115 | 5 | 0 | null | 2011-02-04 21:19:39.52 UTC | 5 | 2018-10-18 20:34:06.68 UTC | 2011-02-04 21:26:33.6 UTC | null | 35,060 | null | 532,968 | null | 1 | 45 | emacs|buffer|eshell | 12,723 | <p>You can call elisp functions directly. So to open a file, call <code>find-file</code> on the filename. Example:</p>
<pre><code>~ $ ls
myfile
~ $ (find-file "myfile")
</code></pre>
<p>Parentheses and quotes are optional, so this works too:</p>
<pre><code>~ $ find-file myfile
</code></pre> |
4,965,863 | How to get a random number in pascal? | <p>I want to get a random number in pascal from between a range. Basically something like this:</p>
<pre><code>r = random(100,200);
</code></pre>
<p>The above code would then have a random number between 100 and 200.</p>
<p>Any ideas?</p>
<p>The built in pascal function only lets you get a number from between 0-your range, while i need to specify the minimum number to return</p> | 4,965,889 | 6 | 2 | null | 2011-02-11 05:16:50.543 UTC | 1 | 2022-01-11 16:56:55.857 UTC | null | null | null | null | 49,153 | null | 1 | 11 | pascal | 62,211 | <p>Just get a random number with the correct range (ie 100 to 200 would be range 100) then add the starting value to it</p>
<p>So: <code>random(100) + 100</code> for your example</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.