id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
4,809,729
Cancel split window in Vim
<p>I have split my windows horizontally. Now how can I return to normal mode, i.e. no split window just one window without cancelling all of my open windows. I have 5 and do not want to "quit", just want to get out of split window. </p>
4,809,736
11
1
null
2011-01-26 20:34:01.72 UTC
57
2021-10-27 17:44:14.483 UTC
2015-02-24 21:41:20.67 UTC
null
520,162
null
591,297
null
1
274
vim|split|window
138,309
<p>Press <kbd>Control</kbd>+<kbd>w</kbd>, then hit <kbd>q</kbd> to close each window at a time.</p> <p><strong>Update</strong>: Also consider eckes answer which may be more useful to you, involving <code>:on</code> (read below) if you don't want to do it one window at a time.</p>
4,797,286
Are braces necessary in one-line statements in JavaScript?
<p>I once heard that leaving the curly braces in one-line statements could be harmful in JavaScript. I don't remember the reasoning anymore and a Google search did not help much. </p> <p>Is there anything that makes it a good idea to surround all statements within curly braces in JavaScript?</p> <p>I am asking, because everyone seems to do so.</p>
4,797,293
21
5
null
2011-01-25 18:17:14.467 UTC
23
2020-12-08 07:00:11.897 UTC
2019-03-13 22:07:26.767 UTC
null
1,243,247
null
283,055
null
1
204
javascript
124,942
<h2>No</h2> <p>But they are recommended. If you ever expand the statement you will need them.</p> <p>This is perfectly valid</p> <pre><code>if (cond) alert("Condition met!") else alert("Condition not met!") </code></pre> <p>However it is highly recommended that you always use braces because if you (or someone else) ever expands the statement it will be required.</p> <p>This same practice follows in all C syntax style languages with bracing. C, C++, Java, even PHP all support one line statement without braces. You have to realize that you are only saving <strong>two characters</strong> and with some people's bracing styles you aren't even saving a line. I prefer a full brace style (like follows) so it tends to be a bit longer. The tradeoff is met very well with the fact you have extremely clear code readability.</p> <pre><code>if (cond) { alert("Condition met!") } else { alert("Condition not met!") } </code></pre>
14,853,643
Fill Select2 dropdown box from database in MVC 4
<p>I need help writing the jquery/ajax to fill a <a href="http://ivaynberg.github.io/select2/index.html">Select2</a> dropdown box.</p> <p><em>For those who don't know what <a href="http://ivaynberg.github.io/select2/index.html">Select2</a> is, it is a javascript extension to provide Twitter Bootstrap looks and search / type-ahead functionality to an html select list dropdown box. For more information look at the examples here: <a href="http://ivaynberg.github.io/select2/index.html">Select2 Github page</a></em> <hr> <strong>UPDATED - Solved!</strong></p> <hr> <p>So I finally put this all together, and the solution to my problems was that I was missing functions to format the results and the list selection. The code below produces a functioning <a href="http://ivaynberg.github.io/select2/index.html">Select2</a> dropbox with type-ahead perfectly.</p> <p>Json Method on Controller:</p> <pre><code>public JsonResult FetchItems(string query) { DatabaseContext dbContext = new DatabaseContext(); //init dbContext List&lt;Item&gt; itemsList = dbContext.Items.ToList(); //fetch list of items from db table List&lt;Item&gt; resultsList = new List&lt;Item&gt;; //create empty results list foreach(var item in itemsList) { //if any item contains the query string if (item.ItemName.IndexOf(query, StringComparison.OrdinalIgnoreCase) &gt;= 0) { resultsList.Add(item); //then add item to the results list } } resultsList.Sort(delegate(Item c1, Item c2) { return c1.ItemName.CompareTo(c2.ItemName); }); //sort the results list alphabetically by ItemName var serialisedJson = from result in resultsList //serialise the results list into json select new { name = result.ItemName, //each json object will have id = result.ItemID //these two variables [name, id] }; return Json(serialisedJson , JsonRequestBehavior.AllowGet); //return the serialised results list } </code></pre> <p>The Json controller method above returns a list of serialised Json objects, whose ItemName contains the string 'query' provided (this 'query' comes from the search box in the <a href="http://ivaynberg.github.io/select2/index.html">Select2</a> drop box).</p> <p>The code below is the Javascript in the view(or layout if you prefer) to power the <a href="http://ivaynberg.github.io/select2/index.html">Select2</a> drop box.</p> <p>Javascript:</p> <pre><code>$("#hiddenHtmlInput").select2({ initSelection: function (element, callback) { var elementText = "@ViewBag.currentItemName"; callback({ "name": elementText }); }, placeholder: "Select an Item", allowClear: true, style: "display: inline-block", minimumInputLength: 2, //you can specify a min. query length to return results ajax:{ cache: false, dataType: "json", type: "GET", url: "@Url.Action("JsonControllerMethod", "ControllerName")", data: function (searchTerm) { return { query: searchTerm }; }, results: function (data) { return {results: data}; } }, formatResult: itemFormatResult, formatSelection: function(item){ return item.name; } escapeMarkup: function (m) { return m; } }); </code></pre> <p>Then in the body of the view you need a hidden Input element, which <a href="http://ivaynberg.github.io/select2/index.html">Select2</a> will render the dropbox to.</p> <p>Html:</p> <pre><code>&lt;input id="hiddenHtmlInput" type="hidden" class="bigdrop" style="width: 30%" value=""/&gt; </code></pre> <p>Or attach a MVC Razor html.hidden element to your view model to enable you to post the picked item Id back to the server.</p> <p>Html (MVC Razor):</p> <pre><code>@Html.HiddenFor(m =&gt; m.ItemModel.ItemId, new { id = "hiddenHtmlInput", @class = "bigdrop", style = "width: 30%", placeholder = "Select an Item" }) </code></pre>
14,876,502
3
2
null
2013-02-13 12:31:11.673 UTC
7
2013-05-10 11:06:26.383 UTC
2013-05-10 11:06:26.383 UTC
null
1,197,659
null
1,197,659
null
1
9
asp.net-mvc|jquery|jquery-select2
40,044
<p>Solved! Finally.</p> <p>The full jquery is below, what was needed were two functions to format the returned results from the controller. This is because the dropbox needs some html markup to be wrapped around the results in order to be able to display them.</p> <p>Also contractID was needed as an attribute in the controller as without it results were shown in the dropdown, but they could not be selected.</p> <pre><code>$("#contractName").select2({ placeholder: "Type to find a Contract", allowClear: true, minimumInputLength: 2, ajax: { cache: false, dataType: "json", type: "GET", url: "@Url.Action("FetchContracts", "Leads")", data: function(searchTerm){ return { query: searchTerm }; }, results: function(data){ return { results: data }; } }, formatResult: contractFormatResult, formatSelection: contractFormatSelection, escapeMarkup: function (m) { return m; } }); function contractFormatResult(contract) { var markup = "&lt;table class='contract-result'&gt;&lt;tr&gt;"; if (contract.name !== undefined) { markup += "&lt;div class='contract-name'&gt;" + contract.name + "&lt;/div&gt;"; } markup += "&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;" return markup; } function contractFormatSelection(contract) { return contract.name; } </code></pre>
14,612,460
how to remove the css overflow:hidden of jquery dialog
<p>I want to add a search input and overlap it on title bar of a jQuery dialog but my problems are:</p> <ul> <li>I can't remove the css overflow property of this specific jQuery dialog</li> <li>The Title bar is always at the top of my input search box.</li> </ul> <p>I've also tried this:</p> <pre><code> $('div#viewVoters').attr('style','overflow:visible'); $('#viewVoters').css('overflow',''); $('#viewVoters').remove('style'); </code></pre> <p>Any idea how to remove the css property or any idea how to add a search input to it?</p> <pre><code>&lt;div id="viewVoters" style="width: auto; min-height: 95px; height: auto; overflow: hidden;" class="ui-dialog-content ui-widget-content" scrolltop="0" scrollleft="0"&gt; &lt;/div&gt; </code></pre>
14,612,504
3
0
null
2013-01-30 19:50:47.14 UTC
2
2018-12-19 12:58:45.537 UTC
2013-01-30 19:57:24.36 UTC
null
1,926,958
null
1,926,958
null
1
11
jquery|html|css
43,299
<p>Just override it in your CSS:</p> <pre><code>#viewVoters { overflow: auto !important; /* or 'visible' whatever */ } </code></pre>
14,735,753
How to configure Microsoft JWT with symmetric key?
<p>I'm trying to configure my ASP.NET app to accept a JSON Web Token (JWT) that is signed with a symmetric key. The STS isn't capable of using certificates for this, so we're using their symmetric key support.</p> <p>On my end, I'm using <a href="http://blogs.msdn.com/b/vbertocci/archive/2012/11/20/introducing-the-developer-preview-of-the-json-web-token-handler-for-the-microsoft-net-framework-4-5.aspx">Microsoft's JWT Developer Preview</a>. Unfortunately, I've not seen any examples of how to use that with a symmetric key. After some digging around with various tools, I found the <code>NamedKeyIssuerTokenResolver</code> and discovered that I <em>can</em> configure it to use a symmetric key. For example:</p> <pre><code>&lt;securityTokenHandlers&gt; &lt;add type="Microsoft.IdentityModel.Tokens.JWT.JWTSecurityTokenHandler,Microsoft.IdentityModel.Tokens.JWT" /&gt; &lt;securityTokenHandlerConfiguration&gt; &lt;certificateValidation certificateValidationMode="PeerTrust" /&gt; &lt;issuerTokenResolver type="Microsoft.IdentityModel.Tokens.JWT.NamedKeyIssuerTokenResolver, Microsoft.IdentityModel.Tokens.JWT"&gt; &lt;securityKey symmetricKey="+zqf97FD/xyzzyplugh42ploverFeeFieFoeFooxqjE=" name="https://localhost/TestRelyingParty" /&gt; &lt;/issuerTokenResolver&gt; &lt;/securityTokenHandlerConfiguration&gt; &lt;/securityTokenHandlers&gt; </code></pre> <p>I'm not entirely sure what I'm supposed to use for the <code>name</code> there. Should it be the audience Uri, perhaps the issuer Uri? In any case, I know that if I don't include a <code>name</code>, I get an exception when my program starts because the <code>securityKey</code> element requires that attribute.</p> <p>Whatever the case, this still doesn't resolve the issue. After I authenticate against the STS, I get the following exception:</p> <pre><code>[SecurityTokenValidationException: JWT10310: Unable to validate signature. validationParameters.SigningTokenResolver type: 'Microsoft.IdentityModel.Tokens.JWT.NamedKeyIssuerTokenResolver', was unable to resolve key to a token. The SecurityKeyIdentifier is: 'SecurityKeyIdentifier ( IsReadOnly = False, Count = 1, Clause[0] = Microsoft.IdentityModel.Tokens.JWT.NamedKeyIdentifierClause ) '. validationParameters.SigningToken was null.] Microsoft.IdentityModel.Tokens.JWT.JWTSecurityTokenHandler.ValidateSignature(JWTSecurityToken jwt, TokenValidationParameters validationParameters) +2111 Microsoft.IdentityModel.Tokens.JWT.JWTSecurityTokenHandler.ValidateToken(JWTSecurityToken jwt, TokenValidationParameters validationParameters) +138 Microsoft.IdentityModel.Tokens.JWT.JWTSecurityTokenHandler.ValidateToken(SecurityToken token) +599 System.IdentityModel.Tokens.SecurityTokenHandlerCollection.ValidateToken(SecurityToken token) +135 System.IdentityModel.Services.TokenReceiver.AuthenticateToken(SecurityToken token, Boolean ensureBearerToken, String endpointUri) +117 System.IdentityModel.Services.WSFederationAuthenticationModule.SignInWithResponseMessage(HttpRequestBase request) +698 System.IdentityModel.Services.WSFederationAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs args) +123924 System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +165 </code></pre> <p>Am I missing some other configuration step? Am I putting the wrong thing in the <code>name</code> attribute? Or is this a known bug in the JWT Developer Preview?</p>
14,837,906
5
0
null
2013-02-06 18:00:52.38 UTC
9
2019-12-23 16:03:36.14 UTC
2019-12-23 16:03:36.14 UTC
null
133
null
56,778
null
1
17
.net|wif|jwt
27,877
<h2>Update 2014/02/13:</h2> <p>As @leastprivilege points out below, this is a whole lot easier with the RTM version of the JWT. I strongly suggest that you ignore this and go with the example he provides at <a href="http://leastprivilege.com/2013/07/16/identityserver-using-ws-federation-with-jwt-tokens-and-symmetric-signatures/">http://leastprivilege.com/2013/07/16/identityserver-using-ws-federation-with-jwt-tokens-and-symmetric-signatures/</a>.</p> <p>Note that the original answer below was for the Beta version, Microsoft.IdentityModel.Tokens.JWT. Upgrading to the release version, System.IdentityModel.Tokens.Jwt, required just a little more work. See below.</p> <p>The primary problem turns out to be that the method <code>JWTSecurityTokenHandler.ValidateToken(token)</code> does not fully populate the <code>TokenValidationParameters</code> that it passes to <code>JWTSecurityTokenHandler.ValidateToken(token, validationParameters)</code>. In particular, it doesn't populate the <code>SigningToken</code> member or the <code>ValidIssuers</code> (or <code>ValidIssuer</code>).</p> <p>Interestingly, the configuration I showed in my original question actually is loaded by the token resolver, and is available at runtime, as you can see in the code below.</p> <p>I don't know how to specify the valid issuer string in the configuration file, though. I strongly suspect that there's a place to put that info, but I haven't yet figured out where it belongs.</p> <p>The solution to my problem is to create a custom security token handler that derives from <code>JWTSecurityTokenHandler</code>. Overriding <code>ValidateToken(token, validationParameters)</code> gives me the opportunity to set those parameters that I need, and then call the base class's <code>ValidateToken</code> method.</p> <pre><code>public class CustomJwtSecurityTokenHandler: JWTSecurityTokenHandler { // Override ValidateSignature so that it gets the SigningToken from the configuration if it doesn't exist in // the validationParameters object. private const string KeyName = "https://localhost/TestRelyingParty"; private const string ValidIssuerString = "https://mySTSname/trust"; public override ClaimsPrincipal ValidateToken(JWTSecurityToken jwt, TokenValidationParameters validationParameters) { // set up valid issuers if ((validationParameters.ValidIssuer == null) &amp;&amp; (validationParameters.ValidIssuers == null || !validationParameters.ValidIssuers.Any())) { validationParameters.ValidIssuers = new List&lt;string&gt; {ValidIssuerString}; } // and signing token. if (validationParameters.SigningToken == null) { var resolver = (NamedKeyIssuerTokenResolver)this.Configuration.IssuerTokenResolver; if (resolver.SecurityKeys != null) { List&lt;SecurityKey&gt; skeys; if (resolver.SecurityKeys.TryGetValue(KeyName, out skeys)) { var tok = new NamedKeySecurityToken(KeyName, skeys); validationParameters.SigningToken = tok; } } } return base.ValidateToken(jwt, validationParameters); } } </code></pre> <p>In my Web.config, I just had to change the security token handler:</p> <pre><code> &lt;securityTokenHandlers&gt; &lt;!--&lt;add type="Microsoft.IdentityModel.Tokens.JWT.JWTSecurityTokenHandler,Microsoft.IdentityModel.Tokens.JWT" /&gt;--&gt; &lt;!-- replaces the default JWTSecurityTokenHandler --&gt; &lt;add type="TestRelyingParty.CustomJwtSecurityTokenHandler,TestRelyingParty" /&gt; </code></pre> <p>Nothing like spending three or four days researching a problem that is solved with a couple dozen lines of code . . .</p> <h2>Addition for new version</h2> <p>In June of 2013, Microsoft officially released their JWT. They changed the namespace to System.IdentityModel.Tokens.Jwt. After upgrading to that, the solution above stopped working. To get it working, I had to add the following to my <code>CustomJwtSecurityTokenHandler</code>. That's in addition to the existing code.</p> <pre><code>public override ClaimsPrincipal ValidateToken(JwtSecurityToken jwt) { var vparms = new TokenValidationParameters { AllowedAudiences = Configuration.AudienceRestriction.AllowedAudienceUris.Select(s =&gt; s.ToString()) }; return ValidateToken(jwt, vparms); } </code></pre>
6,211,274
Encryption of contents in compiled iOS app ( IPA )
<p>As IPA structure is just a zipped file containing compiled codes &amp; media contents like images &amp; audio, how can I protect the contents from being extracted and stolen by others? Is there any encryption I can add into the IPA?</p>
6,211,290
1
0
null
2011-06-02 06:38:03.31 UTC
10
2019-11-22 01:51:25.777 UTC
2014-02-13 00:36:11.557 UTC
user244343
null
null
188,331
null
1
10
ios|encryption|ipa
12,113
<p>This answer mentions that the application is already encrypted by the time it gets onto your users' devices: <a href="https://stackoverflow.com/questions/5784169/does-apple-modify-ios-application-executables-on-apps-submitted-to-the-app-store/5784332#5784332">Does Apple modify iOS application executables on apps submitted to the App Store?</a></p> <p>Sorry, that's only the application binary. The other media are not encrypted, and no, there's no way to encrypt the .ipa. You could try encrypting your images and other media on your system, providing a bunch of application code to decrypt those resources when the app runs, and then your decryption code will become a part of the encrypted application binary. You can't submit an encrypted IPA though, it needs to be the file directly output from Xcode.</p> <p>In response to your comment, the one I've used in the past is CommonCrypto. You can use <a href="https://github.com/RNCryptor/RNCryptor-objc" rel="nofollow noreferrer">this crypto library</a> as a starting point. </p> <p>Simple usage example of the above:</p> <pre><code>NSError *error; NSMutableData *encryptedData = [NSMutableData dataWithContentsOfFile:pathToEncryptedFile]; NSData *decryptedData = [RNDecryptor decryptData:encryptedData withPassword:@"SuperSecretDecryptionKey" error:&amp;error]; UIImage *decryptedImage = [UIImage imageWithData:decryptedData]; </code></pre> <p><strong>IMPORTANT NOTE HERE:</strong> IF someone was to run the <code>strings</code> utility on your <code>.app</code> on a jailbroken iphone, or even on an iPhone they have filesystem access to via USB, they will get a list of all strings declared in your app. This includes "SuperSecretDecryptionKey". So you may want to use an integer, floating-point or other constant to do on-the-fly generation of a string decryption key, or make sure that the string you use to decrypt things is exactly the same as a normal system string so no-one suspects it as the true key. Security through obscurity, in this case, is advantageous.</p> <p>To encrypt/decrypt <code>*.strings</code> files, you should encrypt the key and value strings in some manner (maybe one which gives you hexadecimal back, or any alphanumeric characters), and when you want to access a given value, say <code>LicenceNumber</code>, do this:</p> <pre><code>NSError *error; NSData *unencryptedKey = [@"LicenceNumber" dataUsingEncoding:NSUTF8StringEncoding]; NSData *encryptedKey = [RNEncryptor encryptData:unencryptedKey withSettings:kRNCryptorAES256Settings password:@"SuperSecretEncryptionKey" error:&amp;error] NSData *encryptedValue = [[NSBundle mainBundle] localizedStringForKey:[NSString stringWithUTF8String:[encryptedKey bytes]] value:@"No licence" table:@"EncryptedStringsFile"]; NSData *decryptedValue = [RNDecryptor decryptData:encryptedValue withPassword:@"SuperSecretDecryptionKey" error:&amp;error]; </code></pre>
5,733,220
How do I add the MinGW bin directory to my system path?
<p>I am using Windows XP. I am trying to add a new library to <a href="https://en.wikipedia.org/wiki/Dev-C%2B%2B" rel="noreferrer">Dev-C++</a>. For that, I need to install MinGW and then I have been instructed to add the <code>bin</code> directory of MinGW to my system path. But, I don’t know how to do it. Please guide me (step by step) to add this to my system path.</p>
5,733,462
1
0
null
2011-04-20 15:58:30.473 UTC
8
2017-01-07 21:24:40.907 UTC
2017-01-07 21:22:06.02 UTC
null
63,550
null
603,976
null
1
22
c++|windows
125,787
<p>To change the path on Windows&nbsp;XP, follow <a href="http://www.computerhope.com/issues/ch000549.htm" rel="noreferrer">these instructions</a>, and then add the directory where you install MinGW plus <code>bin</code>. Example: if you install MinGW in C:\ then you have to add <code>C:\mingw\bin</code> to your path</p> <p>Just for completeness here are the steps shown on the link:</p> <ol> <li>From the desktop, right-click <em>My Computer</em> and click <em>Properties</em>.</li> <li>In the <em>System Properties</em> window, click on the <em>Advanced</em> tab.</li> <li>In the <em>Advanced</em> section, click the <em>Environment Variables</em> button.</li> <li><p>Finally, in the <em>Environment Variables</em> window, highlight the <em>Path</em> variable in the <em>Systems Variable</em> section and click the <kbd>Edit</kbd> button. Add or modify the path lines with the paths you wish the computer to access. Each different directory is separated with a semicolon as shown below.</p> <p>C:\Program Files;C:\Winnt;C:\Winnt\System32;c:\mingw\bin</p></li> </ol>
53,996,410
compare two dates in Angular 6
<p>I am new to angular 6 ,Here I need to compare to date inputs and find the greatest one.</p> <pre><code>input 1 : 2018-12-29T00:00:00 input 2 : Mon Dec 31 2018 00:00:00 GMT+0530 (India Standard Time) </code></pre> <p>Here I received the <strong>input 1</strong> from mssql database and the <strong>input 2</strong> from the material datepicker .</p> <p>while compare this two dates as below I got false.</p> <pre><code>console.log(mMagazineObject.From &lt; mMagazineObject.To ? true : false); </code></pre> <p>is there any possibility to compare these two date formats .If yes please help me to fix this .</p>
53,996,476
5
2
null
2019-01-01 14:50:46.407 UTC
1
2022-02-16 13:54:08.697 UTC
null
null
null
null
9,956,391
null
1
17
angular|typescript|angular6
68,461
<p>you can use getTime</p> <pre><code>if (input1Date.getTime() &lt; input2Date.getTime()) </code></pre> <p>Note that if your dates are in string format, you first need to parse them to Date</p>
3,108,270
How to write a project Analysis or project brief?
<p>We are a small (15 ppl) webdevelopment/design company with around 8 fulltime LAMP developers. In order to reduce the amount of errors we make and to prevent our budgets overtaking our estimates i've introduced some sort of technical analysis of our projects before development kicks off. This is a no brainer for an application developer but in our sector (webdev) it seems less than common practice. Up until now we just received a small brief our project manager assembled (often less than one page) and jumped head first into development with some catastrophic budgetting failures as a result.</p> <p>In order to tackle this problem i started reading on the subject, i've read CodeComplete2, Pragmatic Programmer and The Mythical Man-month. I think i've grabbed the concepts behind preparing and analysing a new project but i'm lacking practical examples. Does anyone know of an example technical analysis or extensive project brief that i can take a look at in order to better put the stuff i've read to practice? I'm a big fan of learn-by-example, no need to say that :)</p>
3,131,992
2
0
null
2010-06-24 08:22:44.497 UTC
13
2015-09-28 08:20:57 UTC
2010-06-24 08:30:43.45 UTC
null
187,018
null
187,018
null
1
12
project-management|analysis
44,654
<p>Unfortunately most project scope documents are commercially protected so they can't be published, however I'm happy to pile down my experience of what makes a good one and I've included the sort of things I'd hope to see.</p> <p>The main thing to remember is what you're trying to achieve - you're trying to get a common understanding between you and the client about what is happening. Bad estimates aren't just about the difference between what you thought it would take and what it did take, but also about what you thought you were going to deliver and what the client thought you were going to deliver.</p> <p>One way of looking at documenting all this is so you're covered and if the client does come back and go "where's the reporting module" you can just point to the sentence that says "there will be no reporting module" but that's not really it. It's really about having that conversation at the beginning (where it can be constructive) rather than the end (where it's likely to be confrontational). Remember this if your project or account manager starts staying that too much detail sounds negative.</p> <p>So, what should you include:</p> <ul> <li><p>High level description of what is being done - just a couple of paragraphs. It's really not going to provide any detail but it sets the scene. So in this section you say you're building an e-commerce site to sell widgets, that it's a B2C rather than B2B site, that the project covers the complete design and build of the site and so on. A couple of paragraphs at most.</p></li> <li><p>High level functional requirements - bullet points outlining the key features which will be built / designed. For each data entity included whether it's create, read, update and / or delete as this will help you to better understand the task. So include the ability to create/read/update/delete users, the ability to create, read and update orders, the ability to create/read/update/delete product categories, the ability to create/read/update/delete products including text, images and video.</p></li> <li><p>Non-functional requirements - another area where loads of stuff gets missed. Non-functional requirements include things like performance, user load, auditing, archive, security and so on. Reporting might fit in here - although it's really functional it's something which sort of gets forgotten as it's often something which supports the systems use rather than being a core part of it. If you're not doing something in a give area (e.g. there will be no audit trails) then state that clearly, perhaps in another section called...</p></li> <li><p>Out of Scope - Things will come up during discussions about whether something (a bit of functionality, an interface to another system) is or isn't included. Write these down! One of the key areas where scope fails in my experience is different recollections of these conversations and getting it on paper up front gets rid or much of that. This is another area where reporting can come in (they'll know they want reports but not what so it kind of drifts then you deliver and they ask where they are), but also user management (password reset?) and security.</p></li> <li><p>Assumptions - At this point during the project you're going to have insufficient information to come up with a really accurate estimate. That's OK, you can fill the gaps in yourself, so long as you make it clear that this is what you've done. So if you're making the assumption that they're providing you with corporate templates for laying things out then write that down. If you think they're providing the copy and images for everything, again write it down.</p></li> </ul> <p>Other sections I'd consider including:</p> <ul> <li><p>Technical platform - if you think it's important describe the technical platform at a high level (in this case LAMP plus any other bits). In my experience this isn't an area where scope creed really occurs but it tends to be two minutes to do so it can't hurt.</p></li> <li><p>Interfaces to other systems - In my experience one the things which adds complexity to any project is things over which you do not have complete control, and one of the key areas this happens is interfaces to other systems. Where you're dealing with these it's always best to list the systems, the type of interface and what interactions are going to take place. So, if you're updating their stock system say you are, say it's a web service, say you'll be firing stock queries, updating stock levels and so on.</p></li> <li><p>Dependencies - Again, this is part of the outside of your control thing. If there are other parties contributing to the project (including the client), it can be best to list what you're expecting of them. Who is providing the copy, in what format (is it a nicely structured Excel file that can be easily imported or a million Word documents)? What about a test system for the third party application you're expected to interface with? When do you need these things?</p></li> </ul> <p>Hope this helps.</p> <p>Edit: I've dug out and slightly anonymised a couple of templates I used in my last job. They're internal (that is we were an internal team doing work within the company as opposed to a team doing work for another organisations) but the structure and principals are the same.</p> <p>I've included a project mandate template which is pretty close to the sort of document you want: </p> <p><a href="http://seventeensix.tumblr.com/post/749062608/a-sample-project-mandate-template" rel="noreferrer">http://seventeensix.tumblr.com/post/749062608/a-sample-project-mandate-template</a></p> <p>and a specification template which might also have some bits you'll find useful:</p> <p><a href="http://seventeensix.tumblr.com/post/749077647/a-sample-specification-template" rel="noreferrer">http://seventeensix.tumblr.com/post/749077647/a-sample-specification-template</a></p> <p>The project mandate one contains some real samples from one of the projects there (a very tedious financial systems reconciliation package), both contain structure and pointer as to what goes where with the odd example.</p>
3,044,545
get contact info from android contact picker
<p>I'm trying to call the contact picker, get the persons name, phone and e-mail into strings and send them to another activity using an intent. So far this works:</p> <pre><code>Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); startActivityForResult(intent, 1); // ... @Override public void onActivityResult(int reqCode, int resultCode, Intent data) { super.onActivityResult(reqCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { Uri contactData = data.getData(); Cursor c = managedQuery(contactData, null, null, null, null); if (c.moveToFirst()) { String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); Intent intent = new Intent(CurrentActivity.this, NewActivity.class); intent.putExtra("name", name); startActivityForResult(intent, 0); } } } </code></pre> <p>But if i add in:</p> <pre><code>String number = c.getString(c.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER)); </code></pre> <p>it force closes</p> <p>Maybe theres another way to get their number?</p>
3,044,835
2
0
null
2010-06-15 11:05:51.843 UTC
32
2016-08-16 20:32:07.473 UTC
2013-04-08 18:46:43.957 UTC
null
1,401,895
null
364,727
null
1
37
android|contacts|contactscontract|google-contacts-api
43,732
<p><strong>Phone Numbers</strong></p> <p>Phone numbers are stored in their own table and need to be queried separately. To query the phone number table use the URI stored in the SDK variable ContactsContract.CommonDataKinds.Phone.CONTENT_URI. Use a WHERE conditional to get the phone numbers for the specified contact. </p> <pre><code> if (Integer.parseInt(cur.getString( cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) &gt; 0) { Cursor pCur = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null); while (pCur.moveToNext()) { // Do something with phones } pCur.close(); } </code></pre> <p>Perform a second query against the Android contacts SQLite database. The phone numbers are queried against the URI stored in ContactsContract.CommonDataKinds.Phone.CONTENT_URI. The contact ID is stored in the phone table as ContactsContract.CommonDataKinds.Phone.CONTACT_ID and the WHERE clause is used to limit the data returned.</p> <p><strong>Email Addresses</strong></p> <p>Querying email addresses is similar to phone numbers. A query must be performed to get email addresses from the database. Query the URI stored in ContactsContract.CommonDataKinds.Email.CONTENT_URI to query the email address table. </p> <pre><code>Cursor emailCur = cr.query( ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{id}, null); while (emailCur.moveToNext()) { // This would allow you get several email addresses // if the email addresses were stored in an array String email = emailCur.getString( emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)); String emailType = emailCur.getString( emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE)); } emailCur.close(); </code></pre> <p>As with the phone query the field names for the email table are also stored under ContactsContract.CommonDataKinds. The email query is performed on the URI in ContactsContract.CommonDataKinds.Email.CONTENT_URI and the WHERE clause has to match the ContactsContract.CommonDataKinds.Email.CONTACT_ID field. Since multiple email addresses can be stored loop through the records returned in the Cursor.</p> <p>More tutorials <a href="http://www.higherpass.com/Android/Tutorials/Working-With-Android-Contacts/1/" rel="noreferrer">here</a></p> <p>This method requires Android API version 5 or higher.</p>
39,616,015
SAP HANA create table / insert into new table from select
<p>How to create a new table and insert content of another table?</p>
39,616,016
3
0
null
2016-09-21 12:01:03.747 UTC
null
2020-05-01 11:44:19.717 UTC
null
null
null
null
993,494
null
1
1
sql|create-table|hana
44,649
<pre><code>create column table my_new_table as (select * from my_existing_table) </code></pre>
38,761,021
does Any == Object
<p>The following code in kotlin:</p> <pre><code>Any().javaClass </code></pre> <p>Has value of <code>java.lang.Object</code>. Does that mean <code>Any</code> and <code>Object</code> are the same class? What are their relations?</p>
38,761,552
5
1
null
2016-08-04 07:27:55.45 UTC
3
2021-05-22 02:08:19.033 UTC
null
null
null
null
411,965
null
1
56
kotlin
18,208
<p>No.</p> <p>From the <a href="https://kotlinlang.org/docs/reference/classes.html" rel="noreferrer">Kotlin docs</a> (Emphasis mine)</p> <blockquote> <p>All classes in Kotlin have a common superclass <code>Any</code>, that is a default super for a class with no supertypes declared:</p> <p><code>class Example // Implicitly inherits from Any</code></p> <p><strong><code>Any</code> is not <code>java.lang.Object</code></strong>; in particular, it does not have any members other than <code>equals()</code>, <code>hashCode()</code> and <code>toString()</code>. Please consult the Java interoperability section for more details.</p> </blockquote> <p>Further, from the section on mapped types we find:</p> <blockquote> <p>Kotlin treats some Java types specially. Such types are not loaded from Java “as is”, but are mapped to corresponding Kotlin types. The mapping only matters at compile time, the runtime representation remains unchanged. Java’s primitive types are mapped to corresponding Kotlin types (keeping platform types in mind):</p> <p>...</p> <p><code>java.lang.Object</code> <code>kotlin.Any!</code></p> </blockquote> <p>This says that at <strong>runtime</strong> <code>java.lang.Object</code> and <code>kotlin.Any!</code> are treated the same. But the <code>!</code> also means that the type is a platform type, which has implication with respect to disabling null checks etc.</p> <blockquote> <p>Any reference in Java may be null, which makes Kotlin’s requirements of strict null-safety impractical for objects coming from Java. Types of Java declarations are treated specially in Kotlin and called platform types. Null-checks are relaxed for such types, so that safety guarantees for them are the same as in Java (see more below).</p> <p>...</p> <p>When we call methods on variables of platform types, Kotlin does not issue nullability errors at compile time, but the call may fail at runtime, because of a null-pointer exception or an assertion that Kotlin generates to prevent nulls from propagating:</p> </blockquote>
2,579,290
Looping through recordset with VBA
<p>I am trying to assign salespeople (rsSalespeople) to customers (rsCustomers) in a round-robin fashion in the following manner:</p> <ol> <li>Navigate to first Customer, assign the first SalesPerson to the Customer.</li> <li>Move to Next Customer. If rsSalesPersons is not at EOF, move to Next SalesPerson; if rsSalesPersons is at EOF, MoveFirst to loop back to the first SalesPerson. Assign this (current) SalesPerson to the (current) Customer.</li> <li>Repeat step 2 until rsCustomers is at EOF (EOF = True, i.e. End-Of-Recordset).</li> </ol> <p>It's been awhile since I dealt with VBA, so I'm a bit rusty, but here is what I have come up with, so far:</p> <pre><code>Private Sub Command31_Click() 'On Error GoTo ErrHandler Dim intCustomer As Integer Dim intSalesperson As Integer Dim rsCustomers As DAO.Recordset Dim rsSalespeople As DAO.Recordset Dim strSQL As String strSQL = "SELECT CustomerID, SalespersonID FROM Customers WHERE SalespersonID Is Null" Set rsCustomers = CurrentDb.OpenRecordset(strSQL) strSQL = "SELECT SalespersonID FROM Salespeople" Set rsSalespeople = CurrentDb.OpenRecordset(strSQL) rsCustomers.MoveFirst rsSalespeople.MoveFirst Do While Not rsCustomers.EOF intCustomer = rsCustomers!CustomerID intSalesperson = rsSalespeople!SalespersonID strSQL = "UPDATE Customers SET SalespersonID = " &amp; intSalesperson &amp; " WHERE CustomerID = " &amp; intCustomer DoCmd.RunSQL (strSQL) rsCustomers.MoveNext If Not rsSalespeople.EOF Then rsSalespeople.MoveNext Else rsSalespeople.MoveFirst End If Loop ExitHandler: Set rsCustomers = Nothing Set rsSalespeople = Nothing Exit Sub ErrHandler: MsgBox (Err.Description) Resume ExitHandler End Sub </code></pre> <p>My tables are defined like so:</p> <pre><code>Customers --CustomerID --Name --SalespersonID Salespeople --SalespersonID --Name </code></pre> <p>With ten customers and 5 salespeople, my intended result would like like:</p> <pre><code>CustomerID--Name--SalespersonID 1---A---1 2---B---2 3---C---3 4---D---4 5---E---5 6---F---1 7---G---2 8---H---3 9---I---4 10---J---5 </code></pre> <p>The above code works for the intitial loop through the Salespeople recordset, but errors out when the end of the recordset is found. Regardless of the EOF, it appears it still tries to execute the rsSalespeople.MoveFirst command.</p> <p>Am I not checking for the rsSalespeople.EOF properly? Any ideas to get this code to work?</p>
2,579,481
1
2
null
2010-04-05 15:44:07.223 UTC
3
2010-04-05 17:55:07.217 UTC
2010-04-05 16:23:04.383 UTC
null
146,694
null
146,694
null
1
3
sql|ms-access|vba|loops|recordset
66,623
<p>rsSalespeople.EOF doesn't indicate when you are on the last row, it indicates when you are PAST the last row. </p> <p>So when your conditional hits the last salesperson EOF is false so it does a movenext (making EOF true) then the next pass through the loop is operating on the "EOF row" of rsSalespeople which you can't pull values from, hence the error.</p> <p>Try this instead: </p> <pre><code>rsSalespeople.MoveNext If (rsSalespeople.EOF) Then rsSalespeople.MoveFirst End If </code></pre>
29,323,982
Error: Cannot find module '../lib/cli'
<p>I'm completely new to javascript development and I'm getting the following error as I work my way through the backbone_blueprints book. Here is the error I get:</p> <pre><code>&gt; simple-blog@0.1.0 start /Users/noahc/Projects/backbone_blueprints/blog &gt; nodemon server.js module.js:340 throw err; ^ Error: Cannot find module '../lib/cli' at Function.Module._resolveFilename (module.js:338:15) at Function.Module._load (module.js:280:25) at Module.require (module.js:364:17) at require (module.js:380:17) at Object.&lt;anonymous&gt; (/Users/noahc/Projects/backbone_blueprints/blog/node_modules/.bin/nodemon:3:11) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) npm ERR! Darwin 14.1.0 npm ERR! argv "node" "/usr/local/bin/npm" "start" npm ERR! node v0.10.33 npm ERR! npm v2.1.11 npm ERR! code ELIFECYCLE npm ERR! simple-blog@0.1.0 start: `nodemon server.js` npm ERR! Exit status 8 npm ERR! npm ERR! Failed at the simple-blog@0.1.0 start script 'nodemon server.js'. npm ERR! This is most likely a problem with the simple-blog package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! nodemon server.js npm ERR! You can get their info via: npm ERR! npm owner ls simple-blog npm ERR! There is likely additional logging output above. npm ERR! Please include the following file with any support request: npm ERR! /Users/noahc/Projects/backbone_blueprints/blog/npm-debug.log ☹ ~/Projects/backbone_blueprints/blog npm install ruby-2.1.3 npm WARN package.json simple-blog@0.1.0 No repository field. npm WARN package.json simple-blog@0.1.0 No README data </code></pre> <p>Here is the debug log:</p> <pre><code>0 info it worked if it ends with ok 1 verbose cli [ 'node', '/usr/local/bin/npm', 'install' ] 2 info using npm@2.1.11 3 info using node@v0.10.33 4 verbose node symlink /usr/local/bin/node 5 error install Couldn't read dependencies 6 verbose stack Error: ENOENT, open '/Users/noahc/Projects/backbone_blueprints/package.json' 7 verbose cwd /Users/noahc/Projects/backbone_blueprints 8 error Darwin 14.1.0 9 error argv "node" "/usr/local/bin/npm" "install" 10 error node v0.10.33 11 error npm v2.1.11 12 error path /Users/noahc/Projects/backbone_blueprints/package.json 13 error code ENOPACKAGEJSON 14 error errno 34 15 error package.json ENOENT, open '/Users/noahc/Projects/backbone_blueprints/package.json' 15 error package.json This is most likely not a problem with npm itself. 15 error package.json npm can't find a package.json file in your current directory. 16 verbose exit [ 34, true ] </code></pre> <p>And this:</p> <pre><code>☹ ~/Projects/backbone_blueprints/blog which node ruby-2.1.3 /usr/local/bin/node ☺ ~/Projects/backbone_blueprints/blog which npm ruby-2.1.3 /usr/local/bin/npm </code></pre> <p>I thought it might be a path issue and so I added <code>export NODE_PATH=/opt/lib/node_modules</code> to my .zshrc file and sourced it and that seemed to have no impact. </p> <p>Any thoughts on anyway I can troubleshoot this or try to better understand what is actually happening?</p>
29,324,225
13
0
null
2015-03-28 23:46:13.987 UTC
14
2021-10-14 14:28:31.227 UTC
null
null
null
null
417,449
null
1
76
javascript|npm
78,424
<p>I found the fix. I had to install nodemon globally doing this: <code>npm install nodemon -g</code></p>
31,873,098
Is it always bad to use Thread.Sleep()?
<p>I created an extension method for the the class <code>Random</code> which executes an <code>Action</code> (void delegate) at random times:</p> <pre><code>public static class RandomExtension { private static bool _isAlive; private static Task _executer; public static void ExecuteRandomAsync(this Random random, int min, int max, int minDuration, Action action) { Task outerTask = Task.Factory.StartNew(() =&gt; { _isAlive = true; _executer = Task.Factory.StartNew(() =&gt; { ExecuteRandom(min, max, action); }); Thread.Sleep(minDuration); StopExecuter(); }); } private static void StopExecuter() { _isAlive = false; _executer.Wait(); _executer.Dispose(); _executer = null; } private static void ExecuteRandom(int min, int max, Action action) { Random random = new Random(); while (_isAlive) { Thread.Sleep(random.Next(min, max)); action(); } } } </code></pre> <p>It works fine.</p> <p>But is the use of <code>Thread.Sleep()</code> in this example okay, or should you generally never use <code>Thread.Sleep()</code>, what complications could occur ? Are there alternatives?</p>
31,873,159
5
0
null
2015-08-07 08:32:06.027 UTC
3
2015-08-10 07:58:01.96 UTC
2015-08-10 06:41:06.913 UTC
null
5,193,057
null
5,193,057
null
1
35
c#|multithreading|sleep
6,202
<p>Is using <code>Thread.Sleep</code> bad? Generally not, if you really want to suspend the <em>thread</em>. But in this case you don't want to suspend the <em>thread</em>, you want to suspend the <em>task</em>.</p> <p>So in this case, you should use:</p> <pre><code>await Task.Delay(minDuration); </code></pre> <p>This will not suspend the entire thread, but just the single task you want to suspend. All other tasks on the same thread can continue running.</p>
44,404,349
PyQt showing video stream from opencv
<p>Try to link PyQt and Opencv video feed, can't understand how to apply while loop for continuously streaming video. It just take a still picture.Please can anyone help to solve the problem.</p> <ul> <li><p>PtQt=5</p></li> <li><p>Python=3.6.1</p></li> </ul> <hr> <pre><code>class App(QWidget): def __init__(self): super().__init__() self.title = 'PyQt5 Video' self.left = 100 self.top = 100 self.width = 640 self.height = 480 self.initUI() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.resize(1800, 1200) #create a label label = QLabel(self) cap = cv2.VideoCapture(0) ret, frame = cap.read() rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) convertToQtFormat = QtGui.QImage(rgbImage.data, rgbImage.shape[1], rgbImage.shape[0], QtGui.QImage.Format_RGB888) convertToQtFormat = QtGui.QPixmap.fromImage(convertToQtFormat) pixmap = QPixmap(convertToQtFormat) resizeImage = pixmap.scaled(640, 480, QtCore.Qt.KeepAspectRatio) QApplication.processEvents() label.setPixmap(resizeImage) self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = App() sys.exit(app.exec_()) </code></pre>
44,404,713
3
0
null
2017-06-07 05:39:40.113 UTC
16
2020-03-08 01:06:44.14 UTC
2018-03-23 00:07:43.863 UTC
null
6,622,587
null
7,205,164
null
1
23
python|opencv|pyqt|pyqt5|qpixmap
58,917
<p>The problem is that the function that obtains the image is executed only once and not updating the label.<br> The correct way is to place it inside a loop, but it will result in blocking the main window. This blocking of main window can be solved by using the <code>QThread</code> class and send through a signal <code>QImage</code> to update the label. For example:</p> <pre class="lang-py prettyprint-override"><code>import cv2 import sys from PyQt5.QtWidgets import QWidget, QLabel, QApplication from PyQt5.QtCore import QThread, Qt, pyqtSignal, pyqtSlot from PyQt5.QtGui import QImage, QPixmap class Thread(QThread): changePixmap = pyqtSignal(QImage) def run(self): cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() if ret: # https://stackoverflow.com/a/55468544/6622587 rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) h, w, ch = rgbImage.shape bytesPerLine = ch * w convertToQtFormat = QImage(rgbImage.data, w, h, bytesPerLine, QImage.Format_RGB888) p = convertToQtFormat.scaled(640, 480, Qt.KeepAspectRatio) self.changePixmap.emit(p) class App(QWidget): def __init__(self): super().__init__() [...] self.initUI() @pyqtSlot(QImage) def setImage(self, image): self.label.setPixmap(QPixmap.fromImage(image)) def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.resize(1800, 1200) # create a label self.label = QLabel(self) self.label.move(280, 120) self.label.resize(640, 480) th = Thread(self) th.changePixmap.connect(self.setImage) th.start() self.show() </code></pre>
28,127,259
Update the constant property of a constraint programmatically in Swift?
<p>I want to animate an object, so I declare a constraint and add it to the view. I then update the <code>constant</code> property of the constraint inside an <code>UIView</code> animation. Why doesn't this code move the object?</p> <pre><code>UIView.animateWithDuration(1, animations: { myConstraint.constant = 0 self.view.updateConstraints(myConstraint) }) </code></pre>
28,127,322
1
0
null
2015-01-24 15:54:50.557 UTC
6
2020-04-28 13:12:52.817 UTC
2017-04-08 07:47:25.543 UTC
null
1,135,714
null
1,135,714
null
1
38
ios|swift|nslayoutconstraint
51,461
<p>In order to declare an animation, you cannot re-define the constraint and call <code>updateConstraints</code>. You are supposed to change the <code>constant</code> of your constraint and follow the format below:</p> <pre class="lang-swift prettyprint-override"><code>self.view.layoutIfNeeded() UIView.animate(withDuration: 1) { self.sampleConstraint.constant = 20 self.view.layoutIfNeeded() } </code></pre>
27,411,826
Detect if checkbox is checked or unchecked in Angular.js ng-change event
<p>I want to detect if a checkbox has been checked or unchecked when a click is happening on the checkbox. </p> <p>This is what I have: </p> <pre><code>&lt;input type="checkbox" ng-model="answers[item.questID]" ng-change="stateChanged()" /&gt; </code></pre> <p>And then in the controller I have:</p> <pre><code>$scope.stateChanged = function () { alert('test'); } </code></pre> <p>I'm able to fire the alert when I do check/uncheck but how can I detect the state of the checkbox? I did research a bit to find a similar issue but I wasn't able to get what I need. </p>
27,411,893
2
0
null
2014-12-10 22:12:27.5 UTC
11
2020-06-06 16:35:25.993 UTC
2020-06-06 16:35:25.993 UTC
null
472,495
null
362,479
null
1
45
javascript|jquery|angularjs|checkbox|angularjs-scope
125,254
<p>You could just use the bound <code>ng-model</code> (<code>answers[item.questID]</code>) value itself in your ng-change method to detect if it has been checked or not.</p> <p>Example:-</p> <pre><code>&lt;input type="checkbox" ng-model="answers[item.questID]" ng-change="stateChanged(item.questID)" /&gt; &lt;!-- Pass the specific id --&gt; </code></pre> <p>and </p> <pre><code>$scope.stateChanged = function (qId) { if($scope.answers[qId]){ //If it is checked alert('test'); } } </code></pre>
39,249,043
Firebase Auth get additional user info (age, gender)
<p>I am using Firebase Authentication for my Android app. Users have the ability to login with multiple providers (Google, Facebook, Twitter).</p> <p>After a successful login, is there a way to get the user gender/birth date from these providers using the Firebase api?</p>
39,281,270
4
0
null
2016-08-31 11:58:16.327 UTC
9
2018-08-04 17:47:03.533 UTC
2016-09-01 08:08:01.91 UTC
null
1,039,278
null
1,039,278
null
1
16
android|firebase-authentication
19,800
<p>Unfortunately, Firebase doesn't have any built-in functionality to get the user's gender/birthdate upon successful login. You would have to retrieve these data from each of the providers yourself. </p> <p>Here is how you might get the user's gender from Google using <a href="https://developers.google.com/people/" rel="nofollow">Google People API</a></p> <pre><code>public class SignInActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, View.OnClickListener { private static final int RC_SIGN_IN = 9001; private GoogleApiClient mGoogleApiClient; private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener mAuthListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_google_sign_in); // We can only get basic information using FirebaseAuth mAuth = FirebaseAuth.getInstance(); mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in to Firebase, but we can only get // basic info like name, email, and profile photo url String name = user.getDisplayName(); String email = user.getEmail(); Uri photoUrl = user.getPhotoUrl(); // Even a user's provider-specific profile information // only reveals basic information for (UserInfo profile : user.getProviderData()) { // Id of the provider (ex: google.com) String providerId = profile.getProviderId(); // UID specific to the provider String profileUid = profile.getUid(); // Name, email address, and profile photo Url String profileDisplayName = profile.getDisplayName(); String profileEmail = profile.getEmail(); Uri profilePhotoUrl = profile.getPhotoUrl(); } } else { // User is signed out of Firebase } } }; // Google sign-in button listener findViewById(R.id.google_sign_in_button).setOnClickListener(this); // Configure GoogleSignInOptions GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.server_client_id)) .requestServerAuthCode(getString(R.string.server_client_id)) .requestEmail() .requestScopes(new Scope(PeopleScopes.USERINFO_PROFILE)) .build(); // Build a GoogleApiClient with access to the Google Sign-In API and the // options specified by gso. mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, this) .addOnConnectionFailedListener(this) .addConnectionCallbacks(this) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.google_sign_in_button: signIn(); break; } } private void signIn() { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); } @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); if (result.isSuccess()) { // Signed in successfully GoogleSignInAccount acct = result.getSignInAccount(); // execute AsyncTask to get gender from Google People API new GetGendersTask().execute(acct); // Google Sign In was successful, authenticate with Firebase firebaseAuthWithGoogle(acct); } } } class GetGendersTask extends AsyncTask&lt;GoogleSignInAccount, Void, List&lt;Gender&gt;&gt; { @Override protected List&lt;Gender&gt; doInBackground(GoogleSignInAccount... googleSignInAccounts) { List&lt;Gender&gt; genderList = new ArrayList&lt;&gt;(); try { HttpTransport httpTransport = new NetHttpTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); //Redirect URL for web based applications. // Can be empty too. String redirectUrl = "urn:ietf:wg:oauth:2.0:oob"; // Exchange auth code for access token GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest( httpTransport, jsonFactory, getApplicationContext().getString(R.string.server_client_id), getApplicationContext().getString(R.string.server_client_secret), googleSignInAccounts[0].getServerAuthCode(), redirectUrl ).execute(); GoogleCredential credential = new GoogleCredential.Builder() .setClientSecrets( getApplicationContext().getString(R.string.server_client_id), getApplicationContext().getString(R.string.server_client_secret) ) .setTransport(httpTransport) .setJsonFactory(jsonFactory) .build(); credential.setFromTokenResponse(tokenResponse); People peopleService = new People.Builder(httpTransport, jsonFactory, credential) .setApplicationName("My Application Name") .build(); // Get the user's profile Person profile = peopleService.people().get("people/me").execute(); genderList.addAll(profile.getGenders()); } catch (IOException e) { e.printStackTrace(); } return genderList; } @Override protected void onPostExecute(List&lt;Gender&gt; genders) { super.onPostExecute(genders); // iterate through the list of Genders to // get the gender value (male, female, other) for (Gender gender : genders) { String genderValue = gender.getValue(); } } } } </code></pre> <p>You can find more information on <a href="https://developers.google.com/android/guides/api-client" rel="nofollow">Accessing Google APIs</a></p>
3,198,947
can I override z-index inheritance from parent element?
<p>Is there any way to override z-index inheritance from parent elements when using absolute position. I want 2222 div to be on top of 0000 div:</p> <pre><code>&lt;div style="background-color:green; z-index:10; position:relative"&gt; OOOO &lt;/div&gt; &lt;div style="background-color:yellow; z-index:5; position:relative"&gt; 1111 &lt;div style="position:absolute; background-color:red; z-index:15; top:-8px; left:20px"&gt; 2222 &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I can not change z-index of 0000 or 1111 divs and I am trying to position my 2222 element relative to 1111 element.</p>
3,199,134
1
0
null
2010-07-07 21:23:41.733 UTC
5
2012-11-25 22:11:37.543 UTC
2012-11-25 22:11:37.543 UTC
null
7,382
null
385,959
null
1
34
css|position|z-index
28,629
<p>I believe z-index is relative to the nearest positioned element. So, if you had two divs inside the "1111" div, they could be z-index'd relative to each other, but since 2222 is a child of 1111, it cannot be z-indexed relative to 0000, and will always be above 1111.</p>
2,570,679
Serialization with Qt
<p>I am programming a GUI with Qt library. In my GUI I have a huge std::map.</p> <p>"MyType" is a class that has different kinds of fields.</p> <p>I want to serialize the std::map. How can I do that? Does Qt provides us with neccesary features?</p>
2,571,212
1
0
null
2010-04-03 08:37:25.367 UTC
23
2017-01-08 12:35:40.977 UTC
2013-03-27 12:29:10.057 UTC
null
163,394
null
163,394
null
1
53
c++|qt|serialization|qt4
42,324
<p>QDataStream handles a variety of C++ and Qt data types. The complete list is available at <a href="http://doc.qt.io/qt-4.8/datastreamformat.html" rel="noreferrer">http://doc.qt.io/qt-4.8/datastreamformat.html</a>. We can also add support for our own custom types by overloading the &lt;&lt; and >> operators. Here's the definition of a custom data type that can be used with QDataStream:</p> <pre><code>class Painting { public: Painting() { myYear = 0; } Painting(const QString &amp;title, const QString &amp;artist, int year) { myTitle = title; myArtist = artist; myYear = year; } void setTitle(const QString &amp;title) { myTitle = title; } QString title() const { return myTitle; } ... private: QString myTitle; QString myArtist; int myYear; }; QDataStream &amp;operator&lt;&lt;(QDataStream &amp;out, const Painting &amp;painting); QDataStream &amp;operator&gt;&gt;(QDataStream &amp;in, Painting &amp;painting); </code></pre> <p>Here's how we would implement the &lt;&lt; operator:</p> <pre><code>QDataStream &amp;operator&lt;&lt;(QDataStream &amp;out, const Painting &amp;painting) { out &lt;&lt; painting.title() &lt;&lt; painting.artist() &lt;&lt; quint32(painting.year()); return out; } </code></pre> <p>To output a Painting, we simply output two QStrings and a quint32. At the end of the function, we return the stream. This is a common C++ idiom that allows us to use a chain of &lt;&lt; operators with an output stream. For example:</p> <p>out &lt;&lt; painting1 &lt;&lt; painting2 &lt;&lt; painting3;</p> <p>The implementation of operator>>() is similar to that of operator&lt;&lt;():</p> <pre><code>QDataStream &amp;operator&gt;&gt;(QDataStream &amp;in, Painting &amp;painting) { QString title; QString artist; quint32 year; in &gt;&gt; title &gt;&gt; artist &gt;&gt; year; painting = Painting(title, artist, year); return in; } </code></pre> <p>This is from: C++ GUI Programming with Qt 4 By Jasmin Blanchette, Mark Summerfield </p>
38,559,755
How to get current available GPUs in tensorflow?
<p>I have a plan to use distributed TensorFlow, and I saw TensorFlow can use GPUs for training and testing. In a cluster environment, each machine could have 0 or 1 or more GPUs, and I want to run my TensorFlow graph into GPUs on as many machines as possible.</p> <p>I found that when running <code>tf.Session()</code> TensorFlow gives information about GPU in the log messages like below:</p> <pre><code>I tensorflow/core/common_runtime/gpu/gpu_init.cc:126] DMA: 0 I tensorflow/core/common_runtime/gpu/gpu_init.cc:136] 0: Y I tensorflow/core/common_runtime/gpu/gpu_device.cc:838] Creating TensorFlow device (/gpu:0) -&gt; (device: 0, name: GeForce GTX 1080, pci bus id: 0000:01:00.0) </code></pre> <p>My question is how do I get information about current available GPU from TensorFlow? I can get loaded GPU information from the log, but I want to do it in a more sophisticated, programmatic way. I also could restrict GPUs intentionally using the CUDA_VISIBLE_DEVICES environment variable, so I don't want to know a way of getting GPU information from OS kernel.</p> <p>In short, I want a function like <code>tf.get_available_gpus()</code> that will return <code>['/gpu:0', '/gpu:1']</code> if there are two GPUs available in the machine. How can I implement this?</p>
38,580,201
14
1
null
2016-07-25 04:30:38.39 UTC
63
2022-04-03 20:48:48.993 UTC
2016-07-26 02:37:25.15 UTC
null
3,574,081
null
2,728,425
null
1
223
python|gpu|tensorflow
361,910
<p>There is an undocumented method called <a href="https://github.com/tensorflow/tensorflow/blob/d42facc3cc9611f0c9722c81551a7404a0bd3f6b/tensorflow/python/client/device_lib.py#L27" rel="noreferrer"><code>device_lib.list_local_devices()</code></a> that enables you to list the devices available in the local process. (<strong>N.B.</strong> As an undocumented method, this is subject to backwards incompatible changes.) The function returns a list of <a href="https://github.com/tensorflow/tensorflow/blob/8a4f6abb395b3f1bca732797068021c786c1ec76/tensorflow/core/framework/device_attributes.proto" rel="noreferrer"><code>DeviceAttributes</code> protocol buffer</a> objects. You can extract a list of string device names for the GPU devices as follows:</p> <pre><code>from tensorflow.python.client import device_lib def get_available_gpus(): local_device_protos = device_lib.list_local_devices() return [x.name for x in local_device_protos if x.device_type == 'GPU'] </code></pre> <p>Note that (at least up to TensorFlow 1.4), calling <code>device_lib.list_local_devices()</code> will run some initialization code that, by default, will allocate all of the GPU memory on all of the devices (<a href="https://github.com/tensorflow/tensorflow/issues/9374" rel="noreferrer">GitHub issue</a>). To avoid this, first create a session with an explicitly small <code>per_process_gpu_fraction</code>, or <code>allow_growth=True</code>, to prevent all of the memory being allocated. See <a href="https://stackoverflow.com/q/34199233/3574081">this question</a> for more details.</p>
41,883,573
Melt using patterns when variable names contain string information - avoid coercion to numeric
<p>I am using the <code>patterns()</code> argument in <code>data.table::melt()</code> to melt data that has columns that have several easily-defined patterns. It is working, but I'm not seeing how I can create a character index variable instead of the default numeric breakdown.</p> <p>For example, in data set 'A', the dog and cat column names have numeric suffixes (e.g. 'dog_1', 'cat_2'), which are handled correctly in <code>melt</code> (see the resulting 'variable' column):</p> <pre><code>A = data.table(idcol = c(1:5), dog_1 = c(1:5), cat_1 = c(101:105), dog_2 = c(6:10), cat_2 = c(106:110), dog_3 = c(11:15), cat_3 = c(111:115)) head(melt(A, measure = patterns(&quot;^dog&quot;, &quot;^cat&quot;), value.name = c(&quot;dog&quot;, &quot;cat&quot;))) idcol variable dog cat 1: 1 1 1 101 2: 2 1 2 102 3: 3 1 3 103 4: 4 1 4 104 5: 5 1 5 105 6: 1 2 6 106 </code></pre> <p>However, in data set 'B', the suffix of dog and cat columns is a string (e.g. 'dog_one', 'cat_two'). Such suffixes are converted to a numeric representation in <code>melt</code>, see the &quot;variable&quot; column.</p> <pre><code>B = data.table(idcol = c(1:5), dog_one = c(1:5), cat_one = c(101:105), dog_two = c(6:10), cat_two = c(106:110), dog_three = c(11:15), cat_three = c(111:115)) head(melt(B, measure = patterns(&quot;^dog&quot;, &quot;^cat&quot;), value.name = c(&quot;dog&quot;, &quot;cat&quot;))) idcol variable dog cat 1: 1 1 1 101 2: 2 1 2 102 3: 3 1 3 103 4: 4 1 4 104 5: 5 1 5 105 6: 1 2 6 106 </code></pre> <p>How can I fill the &quot;variable&quot; column with the correct string suffixes one/two/three instead of 1/2/3?</p>
41,884,029
1
0
null
2017-01-26 21:48:28.563 UTC
8
2021-07-09 10:36:18.843 UTC
2021-07-09 10:36:18.843 UTC
null
1,851,712
null
3,311,915
null
1
10
r|data.table|melt
803
<p>From <code>data.table 1.14.1</code> (in development; <a href="https://github.com/Rdatatable/data.table/wiki/Installation#v1141-in-development--" rel="nofollow noreferrer">installation</a>), the new function <code>measure</code> makes it much easier to melt data with concatenated variable names to a desired format (see <code>?measure</code>.</p> <p>The <code>sep</code>arator argument is used to create different groups of <code>measure.vars</code>. In the <code>...</code> argument, we further specify the fate of the values corresponding to the groups generated by <code>sep</code>.</p> <p>In OP, the variable names are of the form <code>species_number</code>, e.g. <code>dog_one</code>. Thus, we need two symbols in <code>...</code> to specify how groups <em>before</em> and <em>after</em> the <code>sep</code>arator should be treated, one for the species (dog or cat) and one for the numbers (one-three).</p> <p>If a symbol in <code>...</code> is set to <code>value.name</code>, then &quot;<code>melt</code> returns <em>multiple</em> value columns (with names defined by the unique values in that group)&quot;. Thus, because you want multiple columns for each species, the <em>first</em> group defined by the separator, the <em>first</em> symbol in <code>...</code> should be <code>value.name</code>.</p> <p>The <em>second</em> group, after the separator, are the numbers, so this is specified as the second symbol in <code>...</code>. We want in a single value column for the numbers, so here we specify the desired column name of the output variable, e.g. &quot;nr&quot;.</p> <pre><code>melt(B, measure.vars = measure(value.name, nr, sep = &quot;_&quot;)) idcol nr dog cat # 1: 1 one 1 101 # 2: 2 one 2 102 # 3: 3 one 3 103 # 4: 4 one 4 104 # 5: 5 one 5 105 # 6: 1 two 6 106 # 7: 2 two 7 107 # 8: 3 two 8 108 # 9: 4 two 9 109 # 10: 5 two 10 110 # 11: 1 three 11 111 # 12: 2 three 12 112 # 13: 3 three 13 113 # 14: 4 three 14 114 # 15: 5 three 15 115 </code></pre> <hr /> <p>Pre <code>data.table 1.14.1</code></p> <p>There might be easier ways, but this seems to work:</p> <pre><code># grab suffixes of 'variable' names suff &lt;- unique(sub('^.*_', '', names(B[ , -1]))) # suff &lt;- unique(tstrsplit(names(B[, -1]), &quot;_&quot;)[[2]]) # melt B2 &lt;- melt(B, measure = patterns(&quot;^dog&quot;, &quot;^cat&quot;), value.name = c(&quot;dog&quot;, &quot;cat&quot;)) # replace factor levels in 'variable' with the suffixes setattr(B2$variable, &quot;levels&quot;, suff) B2 # idcol variable dog cat # 1: 1 one 1 101 # 2: 2 one 2 102 # 3: 3 one 3 103 # 4: 4 one 4 104 # 5: 5 one 5 105 # 6: 1 two 6 106 # 7: 2 two 7 107 # 8: 3 two 8 108 # 9: 4 two 9 109 # 10: 5 two 10 110 # 11: 1 three 11 111 # 12: 2 three 12 112 # 13: 3 three 13 113 # 14: 4 three 14 114 # 15: 5 three 15 115 </code></pre> <p>Two related <code>data.table</code> issues:</p> <p><a href="https://github.com/Rdatatable/data.table/issues/3396" rel="nofollow noreferrer">melt.data.table should offer <code>variable</code> to match on the name, rather than the number</a></p> <p><a href="https://github.com/Rdatatable/data.table/issues/1547" rel="nofollow noreferrer">FR: expansion of melt functionality for handling names of output</a>.</p> <hr /> <p>This is one of the (rare) instances where I believe good'ol <code>base::reshape</code> is cleaner. Its <code>sep</code> argument comes in handy here — both the names of the 'value' column and the levels of the 'variable' columns are generated in one go:</p> <pre><code>reshape(data = B, varying = names(B[ , -1]), sep = &quot;_&quot;, direction = &quot;long&quot;) </code></pre>
49,442,165
How do you add borderRadius to ImageBackground?
<p>The React Native <code>ImageBackground</code> component is supposed to accept the same prop signature as <code>Image</code>. However, it doesn't seem to accept <code>borderRadius</code>.</p> <p>This has no affect.</p> <pre><code>&lt;ImageBackground style={{height: 100, width: 100, borderRadius: 6}} source={{ uri: 'www.imageislocatedhere.com }} &gt; </code></pre> <p>How do you change the border radius of an <code>ImageBackground</code>?</p>
49,442,166
3
0
null
2018-03-23 04:02:30.773 UTC
3
2021-07-07 13:24:29.52 UTC
null
null
null
null
25,197
null
1
61
react-native
34,485
<p><sup><em>This took some digging so posting Q&amp;A for others to find.</em></sup></p> <p><code>ImageBackground</code> is basically a <code>&lt;View&gt;</code> wrapping an <code>&lt;Image&gt;</code>.<br /> The <code>style</code> prop only passes height and width to the <code>&lt;Image&gt;</code>.</p> <p>To pass other <code>style</code> props use <code>imageStyle</code>.</p> <pre class="lang-js prettyprint-override"><code>&lt;ImageBackground style={{height: 100, width: 100}} imageStyle={{ borderRadius: 6}} source={{ uri: 'www.imageislocatedhere.com }} &gt; </code></pre> <p><a href="https://github.com/facebook/react-native/blob/master/Libraries/Image/ImageBackground.js" rel="noreferrer">The details are documented in the source code</a>.</p>
49,346,733
How to downgrade vscode
<p>I am experiencing a problem with debugging in vscode just after the last update. There's something going on (<a href="https://github.com/Microsoft/vscode/issues/45657" rel="noreferrer">https://github.com/Microsoft/vscode/issues/45657</a>)</p> <p>I'd like to check the previous version to see if my case is a problem here or in vscode but I can not find instructions on how to downgrade (I suppose it's possible)</p>
49,347,158
3
1
null
2018-03-18 10:16:18.663 UTC
23
2021-11-03 06:58:35.33 UTC
null
null
null
null
430,531
null
1
136
visual-studio-code|downgrade
108,854
<p>Previous versions of Visual Studio Code can be downloaded here:</p> <p><a href="https://code.visualstudio.com/updates/" rel="noreferrer">https://code.visualstudio.com/updates/</a></p> <p><strong>Pick the version you want from the list on the left</strong>, and then click on the download link for your OS as shown here:</p> <p><a href="https://i.stack.imgur.com/G2fEs.png" rel="noreferrer"><img src="https://i.stack.imgur.com/G2fEs.png" alt="enter image description here"></a></p> <p><strong>You should disable auto update</strong> (as mentioned by Gregory in the comment) to <strong>prevent it from auto updating itself</strong> later upon restart. To do this, go to <em>Preferences</em>, <em>Settings</em> and then search for 'update'. Set it to 'none' as shown below:</p> <p><a href="https://i.stack.imgur.com/0acuR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0acuR.png" alt="Disable auto update"></a></p>
45,123,559
Printing return value in function
<p>The <code>print(result)</code> in my <code>total</code> function isn't printing my result.</p> <p>Shouldn't the <code>sums</code> function return the result value to the function that called it?</p> <p>This is my code:</p> <pre><code>def main(): #Get the user's age and user's best friend's age. firstAge = int(input("Enter your age: ")) secondAge = int(input("Enter your best friend's age: ")) total(firstAge,secondAge) def total(firstAge,secondAge): sums(firstAge,secondAge) print(result) #The sum function accepts two integers arguments and returns the sum of those arguments as an integer. def sums(num1,num2): result = int(num1+num2) return result main() </code></pre> <p>I'm using Python-3.6.1.</p>
45,123,596
2
1
null
2017-07-15 23:12:50.02 UTC
3
2019-12-17 02:31:11.223 UTC
2017-07-15 23:25:54.133 UTC
null
5,393,381
null
8,304,707
null
1
5
python|function|return
62,504
<p>It does return the result, but you do not assign it to anything. Thus, the result variable is not defined when you try to print it and raises an error.</p> <p>Adjust your total function and assign the value that sums returns to a variable, in this case <code>response</code> for more clarity on the difference to the variable <code>result</code> defined in the scope of the <code>sums</code> function. Once you have assigned it to a variable, you can print it using the variable.</p> <pre><code>def total(firstAge,secondAge): response = sums(firstAge,secondAge) print(response) </code></pre>
22,504,566
Renaming files using node.js
<p>I am quite new in using JS, so I will try to be as specific as I can :)</p> <ul> <li><p>I have a folder with 260 .png files with different country names: <code>Afghanistan.png</code>, <code>Albania.png</code>, <code>Algeria.png</code>, etc.</p></li> <li><p>I have a .json file with a piece of code with all the ISO codes for each country like this:</p></li> </ul> <pre> { "AF" : "Afghanistan", "AL" : "Albania", "DZ" : "Algeria", ... } </pre> <ul> <li>I would like to rename the .png files with their ISO name in low-case. That means I would like to have the following input in my folder with all the <code>.png</code> images: <code>af.png</code>, <code>al.png</code>, <code>dz.png</code>, etc.</li> </ul> <p>I was trying to research by myself how to do this with node.js, but I am a little lost here and I would appreciate some clues a lot.</p> <p>Thanks in advance!</p>
22,504,722
4
0
null
2014-03-19 11:35:09.733 UTC
14
2019-05-14 12:57:05.937 UTC
2014-03-19 11:57:27.38 UTC
null
1,545,777
null
3,437,302
null
1
125
javascript|node.js|rename
153,329
<p>You'll need to use <code>fs</code> for that: <a href="http://nodejs.org/api/fs.html" rel="noreferrer">http://nodejs.org/api/fs.html</a></p> <p>And in particular the <code>fs.rename()</code> function:</p> <pre><code>var fs = require('fs'); fs.rename('/path/to/Afghanistan.png', '/path/to/AF.png', function(err) { if ( err ) console.log('ERROR: ' + err); }); </code></pre> <p>Put that in a loop over your freshly-read JSON object's keys and values, and you've got a batch renaming script.</p> <pre><code>fs.readFile('/path/to/countries.json', function(error, data) { if (error) { console.log(error); return; } var obj = JSON.parse(data); for(var p in obj) { fs.rename('/path/to/' + obj[p] + '.png', '/path/to/' + p + '.png', function(err) { if ( err ) console.log('ERROR: ' + err); }); } }); </code></pre> <p>(This assumes here that your <code>.json</code> file is trustworthy and that it's safe to use its keys and values directly in filenames. If that's not the case, be sure to escape those properly!)</p>
41,744,096
Efficient way to update multiple fields of Django model object
<p>I'm trying to update user in Django database. </p> <p>Fetched data is as follows :</p> <pre><code>fetched_data = { 'id': 1, 'first_name': 'John', 'last_name': 'Doe', 'phone': '+32 12', 'mobile_phone': '+32 13', 'email': 'myemail@hotmail.com', 'username': 'myusername' } </code></pre> <p>I get the user with this <strong>id</strong> as follows : </p> <pre><code>old_user = User.objects.get(pk=fetched_data['id']) </code></pre> <p>If I update the user as follows :</p> <pre><code>old_user.username = fetched_data['username'] old_user.first_name = fetched_data['first_name'] ...... old_user.save() </code></pre> <p>it works fine, but I do not want to do it for every record, thus I tried something like :</p> <pre><code>for fetched_data_key in fetched_data: old_user.fetched_data_key = fetched_data['fetched_data_key'] //old_user[fetched_data_key] = fetched_data['fetched_data_key'] --- I tried this way to old_user.save() </code></pre> <p>But that doesn't work. Any idea how can I update the user without doing it for every record?</p>
41,744,338
5
0
null
2017-01-19 14:22:04.4 UTC
7
2020-12-01 07:22:06.707 UTC
2017-01-19 14:37:14.507 UTC
null
2,063,361
null
3,895,259
null
1
42
python|django
41,643
<p>You can update a row in the database without fetching and deserializing it; <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#update" rel="noreferrer"><code>update()</code></a> can do it. E.g.:</p> <pre><code>User.objects.filter(id=data['id']).update(email=data['email'], phone=data['phone']) </code></pre> <p>This will issue one SQL <code>update</code> statement, and is much faster than the code in your post. It will never fetch the data or waste time creating a <code>User</code> object.</p> <p>You cannot, though, send a whole bunch of update data to the SQL database and ask it to map it to different rows in one go. If you need a massive update like that done very quickly, your best bet is probably inserting the data into a separate table and then <a href="https://stackoverflow.com/a/6258586/223424">update it form a <code>select</code> on that table</a>. Django ORM does not support this, as far as I can tell. </p>
24,700,184
How do I force a vertical scrollbar to appear?
<p>My site has both very short and longer pages. Since I center it in the viewport with <code>margin: 0 auto</code>, it jumps around a few pixels when switching from a page that has a scrollbar to one that hasn't and the other way around.</p> <p>Is there a way to force the vertical scrollbar to always appear, so my site stays put when browsing it?</p>
24,700,199
2
0
null
2014-07-11 14:32:02.83 UTC
11
2014-07-11 14:37:32.74 UTC
null
null
null
null
1,012,942
null
1
83
css|margin
117,151
<p>Give your <code>body</code> tag an <code>overflow: scroll;</code></p> <pre><code>body { overflow: scroll; } </code></pre> <p>or if you only want a vertical scrollbar use <code>overflow-y</code></p> <pre><code>body { overflow-y: scroll; } </code></pre>
46,159,097
Adding headers to postForObject() method of RestTemplate in spring
<p>I am calling web service using below method.</p> <pre><code>ResponseBean responseBean = getRestTemplate() .postForObject(url, customerBean, ResponseBean.class); </code></pre> <p>Now my requirement got changed. I want to send 2 headers with the request. How should I do it?</p> <p>Customer bean is a class where which contain all the data which will be used as request body.</p> <p>How to add headers in this case?</p>
46,159,273
2
0
null
2017-09-11 15:19:40.62 UTC
7
2019-04-26 10:22:59.143 UTC
2018-01-31 07:05:31.133 UTC
null
6,075,912
null
6,075,912
null
1
23
spring|rest|web-services|restful-authentication
53,674
<p>You can use <code>HttpEntity&lt;T&gt;</code> for your purpose. For example:</p> <pre><code>CustomerBean customerBean = new CustomerBean(); // ... HttpHeaders headers = new HttpHeaders(); headers.set("headername", "headervalue"); HttpEntity&lt;CustomerBean&gt; request = new HttpEntity&lt;&gt;(customerBean, headers); ResponseBean response = restTemplate.postForObject(url, request, ResponseBean.class); </code></pre>
2,933,266
GWT vs. Cappuccino
<p>I'm in the planning stage of a web application and I'm trying to choose between GWT and Cappuccino. I have an idea of which one I think is better, but my partner is sold on the other choice. I was hoping to get some feedback on pros and cons for each from people who have used one or the other or both. Thanks in advance for any insight you might have.</p>
2,937,786
3
2
null
2010-05-29 00:31:59.75 UTC
12
2012-10-29 17:23:50.11 UTC
null
null
null
null
185,964
null
1
11
gwt|cappuccino
4,590
<p><strong>Toolkit v/s Framework</strong></p> <p>GWT is a <a href="http://en.wikipedia.org/wiki/Programming_tool" rel="nofollow noreferrer">toolkit</a>. Its strength lies in the tools it provides to create an application. It doesn't provide a framework though. Developers usually build a small framework over GWT to suit their needs. There has been a lot of emphasis on MVP pattern to build apps, but it isn't the only way to use GWT.</p> <p>Cappuccino is a <a href="http://en.wikipedia.org/wiki/Software_framework" rel="nofollow noreferrer">Framework</a>. It has a prescribed way of building applications. Additionally, it provides libraries to perform high level tasks like animation, drag-and-drop undo/redo etc. GWT doesn't provide any libraries for such tasks, though third party libraries are available.</p> <p>This means that Cappuccino apps tend to be richer than corresponding GWT apps.</p> <p><strong>Offline Compilation v/s Runtime Translation</strong></p> <p>GWT believes in making decisions at compile time. Browser detection, I18N, image inlining, generation of sprites, uibinder template evaluation are all performed at compile time. <a href="http://code.google.com/webtoolkit/doc/latest/DevGuideCodingBasicsDeferred.html" rel="nofollow noreferrer">Deferred Binding</a> allows developers to leverage this concept in their own applications. </p> <p><strong>EDIT</strong></p> <p>Cappuccino, by default, does not need compilation. The browser downloads objective-j files, and then the framework translates/interprets them directly at runtime. However, it is possible to <a href="http://cappuccino.org/discuss/2010/04/28/introducing-jake-a-build-tool-for-javascript/" rel="nofollow noreferrer">compile using jake</a>. You can choose from several minifiers/compressors, including <a href="http://code.google.com/closure/compiler/" rel="nofollow noreferrer">google's closure compiler</a>.</p> <p><strike> As a result of this architectural decision, GWT apps tend to be <em>faster at runtime</em> than equivalent Cappuccino apps. However, because of the compile time cost, <em>development tends to be slower</em> than Cappuccino. GWT development plugin somewhat eases this pain, but the cost doesn't go away entirely.</p> <p>Since GWT is a <code>closed-world</code> compiler, it can remove unused code, inline method calls, intern strings and optimize code in ways Cappuccino cannot. If Cappuccino were to introduce a compilation step, it <em>could</em> perform the same optimizations; but to the best of my knowledge there is no way to do the translation at compile time. </strike></p> <p>With the optional compilation step, this point becomes moot. However, cappuccino applications that do not perform such a compilation will have a poor performance as compared to a GWT app.</p> <p><strong>Type Safety</strong></p> <p>GWT is java - and is therefore <a href="http://en.wikipedia.org/wiki/Type_safety" rel="nofollow noreferrer">type safe</a>. Objective J is javascript, and therefore dynamically typed. This has its own <a href="http://en.wikipedia.org/wiki/Type_system" rel="nofollow noreferrer">advantages and disadvantages</a>, and since it is a religious discussion, I will refrain from making a judgement.</p> <p><strong>Debugging</strong></p> <p>GWT provides a browser plugin that helps developers directly debug Java code. In development mode, developers get to see java stack traces. At runtime, however, the generated JS code is obfuscated, and very difficult to debug (though there is a way to tell GWT 'don't obfuscate my code').</p> <p>Using the <a href="https://developers.google.com/web-toolkit/articles/superdevmode" rel="nofollow noreferrer">super-dev-mode</a> it is now possible to debug the Java code directly from the web-browser.</p> <p>Cappuccino doesn't have a development mode, which means you have to use existing tools like firebug to debug. Errors are reported by the browser, and to debug code you have to use JS debuggers.</p> <p><strong>Unit Testing</strong></p> <p>With GWT, you can write pure java unit test cases that do not require a browser to run. This has obvious advantages - speed and ability to reuse existing infrastructure are some of them. When you do need a browser to test, you can choose from GWTTestCase or HTMLUnit. Its also possible to test using Selenium.</p> <p>Cappuccino apps can be tested using <a href="http://wiki.github.com/280north/OJTest/" rel="nofollow noreferrer">OJTest</a>. Unfortunately, I couldn't find much documentation on the subject, so can't comment much. Of course, you can always use Selenium to test your webapp.</p> <p><strong>Interoperability with Javascript</strong></p> <p>GWT provides a way to talk to existing JS libraries - its called <a href="http://code.google.com/webtoolkit/doc/latest/DevGuideCodingBasicsJSNI.html" rel="nofollow noreferrer">Javascript Native Interface</a>. It is mature and works well, but isn't really intuitive. Objective J <em>is</em> javascript, so you don't have to do anything special to inter-operate with Javascript.</p> <p><strong>Vision</strong></p> <p>I can't back this argument, but GWT tends to focus on creating high-performance web applications without caring much about look and feel. They never compromise on performance. Cappuccino on the other hand tends to focus on higher level features and frameworks, and compromise on run time performance. </p> <p>As a result, Cappuccino apps look richer, but take a while to load. GWT apps load and respond faster, but look boring. You can get around both the problems, I am sure - but that's the way it is out-of-the-box.</p> <p><strong>Community Support and Backing</strong></p> <p>GWT is backed by Google. Their commitment to GWT is pretty strong. Newer applications (Wave, Adwords, Orkut) from Google are built on GWT. Google IO has had several sessions on GWT. The <a href="http://groups.google.com/group/Google-Web-Toolkit" rel="nofollow noreferrer">user forum</a> is pretty active and responsive, and the toolkit itself is actively developed and maintained by Google and the open source community. The <a href="http://groups.google.com/group/objectivej" rel="nofollow noreferrer">Cappuccino user group</a> isn't as active, and has far fewer members.</p>
3,119,108
Return custom 403 error page with nginx
<p>Im trying to display the error page in /temp/www/error403.html whenever a 403 error occurs.</p> <p>This should be whenever a user tries to access the site via https (ssl) and it's IP is in the blovkips.conf file, but at the moment it still shows nginx's default error page. I have the same code for my other server (without any blocking) and it works.</p> <p>Is it blocking the IP from accessing the custom 403 page? If so how do I get it to work?</p> <pre><code>server { # ssl listen 443; ssl on; ssl_certificate /etc/nginx/ssl/site.in.crt; ssl_certificate_key /etc/nginx/ssl/site.in.key; keepalive_timeout 70; server_name localhost; location / { root /temp/www; index index.html index.htm; } # redirect server error pages to the static page error_page 403 /error403.html; # location = /error403.html { # root /temp/www; # } # add trailing slash if missing if (-f $document_root/$host$uri) { rewrite ^(.*[^/])$ $1/ permanent; } # list of IPs to block include blockips.conf; } </code></pre> <p><b>Edit:</b> Corrected error_page code from 504 to 403 but I still have the same issue</p>
3,154,509
4
0
null
2010-06-25 15:09:04.527 UTC
4
2019-07-30 15:09:05.683 UTC
2010-07-01 11:41:27.987 UTC
null
138,541
null
138,541
null
1
14
webserver|nginx|http-status-code-403|custom-error-pages
57,063
<p>I did heaps of googling before coming here but did some more just now, within 5 minutes I had my answer :P</p> <p>Seems I'm not the only person to have this issue:</p> <pre><code>error_page 403 /e403.html; location = /e403.html { root html; allow all; } </code></pre> <p><a href="http://www.cyberciti.biz/faq/unix-linux-nginx-custom-error-403-page-configuration/" rel="noreferrer">http://www.cyberciti.biz/faq/unix-linux-nginx-custom-error-403-page-configuration/</a></p> <p>Seems that I was right in thinking that access to my error page was getting blocked.</p>
2,537,620
Immutable type and property in C#
<p>What is meant by immutable type and immutable property in C# ? can you give simple example?</p>
2,537,631
4
0
null
2010-03-29 11:56:54.86 UTC
6
2021-05-27 07:39:39.137 UTC
2012-05-13 10:07:16.717 UTC
null
512,251
null
304,173
null
1
32
c#|types|immutability
19,963
<p>An immutable type is a type of which its properties can only be set at initialization. Once an object is created, nothing can be changed anymore. An immutable property is simply a read-only property.</p> <p>In the following example, <code>ImmutableType</code> is an immutable type with one property <code>Test</code>. Test is a read-only property. It can only be set at construction.</p> <pre><code>class ImmutableType { private readonly string _test; public string Test { get { return _test; } } public ImmutableType(string test) { _test = test; } } </code></pre> <p><strong>See also</strong>: <a href="http://en.wikipedia.org/wiki/Immutable_object" rel="noreferrer">The Wikipedia article</a>, and <a href="https://stackoverflow.com/questions/279507/what-is-meant-by-immutable">some Stack</a> <a href="https://stackoverflow.com/questions/352471/how-do-i-create-an-immutable-class">Overflow questions</a> on the topic. </p>
2,641,236
Make regular expression case insensitive in ASP.NET RegularExpressionValidator
<p>Given this regular expression: <code>"^[0-9]*\s*(lbs|kg|kgs)$"</code> how do I make it case insensitive? I am trying to use this in a .net regular expression validator, so I need to specify case insensitivity in the pattern.</p> <p><strong>I can not use the RegexOptions programatically because I am specifying the regular expression in a RegularExpressionValidator</strong></p>
3,063,373
4
2
null
2010-04-14 21:37:13.71 UTC
6
2022-06-08 20:27:59.193 UTC
2013-02-24 00:20:50.313 UTC
null
292,060
null
9,266
null
1
44
.net|regex|validation
31,282
<p>I found out.</p> <p>Case sensitive: <code>^[0-9]\s(lbs|kg|kgs)$</code></p> <p>Case insensitive: <code>(?i:^[0-9]\s(lbs|kg|kgs)$)</code></p> <p>I believe that this is specific to the .NET implementation of regular expressions. So if you use this in the RegularExpressionValidator you have to turn off client side validation because the javascript regex parser will not recognize the <code>?i</code> token. </p>
74,113
Access the camera with iOS
<p>It seems obvious that some people have been able to figure out how to access the iPhone camera through the SDK (Spore Origins, for example). How can this be done?</p>
74,255
2
0
null
2008-09-16 16:15:04.483 UTC
31
2019-01-10 05:38:00.31 UTC
2019-01-10 05:25:12.903 UTC
null
1,033,581
Jason Francis
5,338
null
1
35
ios|iphone|camera
59,909
<p>You need to use the <code>UIImagePickerController</code> class, basically:</p> <pre><code>UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.delegate = pickerDelegate picker.sourceType = UIImagePickerControllerSourceTypeCamera </code></pre> <p>The <code>pickerDelegate</code> object above needs to implement the following method:</p> <pre><code>- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info </code></pre> <p>The dictionary <code>info</code> will contain entries for the original, and the edited image, keyed with <code>UIImagePickerControllerOriginalImage</code> and <code>UIImagePickerControllerEditedImage</code> respectively. (see <a href="https://developer.apple.com/documentation/uikit/uiimagepickercontrollerdelegate" rel="nofollow noreferrer">https://developer.apple.com/documentation/uikit/uiimagepickercontrollerdelegate</a> and <a href="https://developer.apple.com/documentation/uikit/uiimagepickercontrollerinfokey" rel="nofollow noreferrer">https://developer.apple.com/documentation/uikit/uiimagepickercontrollerinfokey</a> for more details)</p>
3,079,098
The C# using statement, SQL, and SqlConnection
<p>Is this possible using a using statement C# SQL?</p> <pre><code>private static void CreateCommand(string queryString, string connectionString) { using (SqlConnection connection = new SqlConnection( connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); command.Connection.Open(); command.ExecuteNonQuery(); } } </code></pre> <p>What if there’s a error while opening the connection?</p> <p>The using statement is try and finally<br> No catch</p> <p>So if I catch outside the using brackets will the catch catch the connection opening error?</p> <p>If not, how to implement this with using the <code>using</code> statement a shown above?</p>
3,079,141
5
0
null
2010-06-20 11:43:14.69 UTC
3
2016-07-01 11:19:24.293 UTC
2010-08-29 13:20:52.017 UTC
null
63,550
null
287,745
null
1
12
c#|sql|using-statement
44,244
<p>It's possible to do so in C# (I also see that code is exactly shown in MSDN <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx</a>). However, if you need to be defensive and for example log potential exceptions which would help troubleshooting in a production environment, you can take this approach:</p> <pre><code>private static void CreateCommand(string queryString, string connectionString) { using (SqlConnection connection = new SqlConnection( connectionString)) { try { SqlCommand command = new SqlCommand(queryString, connection); command.Connection.Open(); command.ExecuteNonQuery(); } catch (InvalidOperationException) { //log and/or rethrow or ignore } catch (SqlException) { //log and/or rethrow or ignore } catch (ArgumentException) { //log and/or rethrow or ignore } } } </code></pre>
2,935,295
What is the best way of determining a loop invariant?
<p>When using formal aspects to create some code is there a generic method of determining a loop invariant or will it be completely different depending on the problem?</p>
3,414,198
5
0
null
2010-05-29 13:46:44.897 UTC
10
2013-10-03 17:11:41.4 UTC
2013-10-03 17:11:41.4 UTC
null
96,780
null
330,373
null
1
16
loops|invariants|formal-methods|loop-invariant
30,490
<p>It has already been pointed out that one same loop can have several invariants, and that Calculability is against you. It doesn't mean that you cannot try.</p> <p>You are, in fact, looking for an <strong>inductive invariant</strong>: the word invariant may also be used for a property that is true at each iteration but for which is it not enough to know that it hold at one iteration to deduce that it holds at the next. If <strong>I</strong> is an inductive invariant, then any consequence of <strong>I</strong> is an invariant, but may not be an inductive invariant.</p> <p>You are probably trying to get an inductive invariant to prove a certain property (post-condition) of the loop in some defined circumstances (pre-conditions). </p> <p>There are two heuristics that work quite well:</p> <ul> <li><p>start with what you have (pre-conditions), and weaken until you have an inductive invariant. In order to get an intuition how to weaken, apply one or several forward loop iterations and see what ceases to be true in the formula you have.</p></li> <li><p>start with what you want (post-conditions) and strengthen until you have an inductive invariant. To get the intuition how to strengthen, apply one or several loop iterations <strong>backwards</strong> and see what needs to be added so that the post-condition can be deduced.</p></li> </ul> <p>If you want the computer to help you in your practice, I can recommend the <a href="http://frama-c.com/jessie.html" rel="noreferrer">Jessie</a> deductive verification plug-in for C programs of <a href="http://frama-c.com/" rel="noreferrer">Frama-C</a>. There are others, especially for Java and JML annotations, but I am less familiar with them. Trying out the invariants you think of is much faster than working out if they work on paper. I should point out that verifying that a property is an inductive invariant is also undecidable, but modern automatic provers do great on many simple examples. If you decide to go that route, get as many as you can from the list: Alt-ergo, Simplify, Z3.</p> <p>With the optional (and slightly difficult to install) library Apron, Jessie can also <a href="http://frama-c.com/jessie_tutorial_index.html#htoc14" rel="noreferrer">infer some simple invariants automatically</a>.</p>
3,043,654
Why use TagBuilder instead of StringBuilder?
<p>what's the difference in using tag builder and string builder to create a table in a htmlhelper class, or using the HtmlTable?</p> <p>aren't they generating the same thing??</p>
3,043,797
6
0
null
2010-06-15 08:35:56.39 UTC
9
2015-01-25 08:53:59.393 UTC
null
null
null
null
181,771
null
1
42
c#|asp.net-mvc|extension-methods|stringbuilder|tagbuilder
23,305
<p><code>TagBuilder</code> is a class that specially designed for creating html tags and their content. You are right saying that result will be anyway a string and of course you still can use <code>StringBuilder</code> and the result will be the same, but you can do things easier with <code>TagBuilder</code>. Lets say you need to generate a tag: </p> <pre><code>&lt;a href='http://www.stackoverflow.com' class='coolLink'/&gt; </code></pre> <p>Using <code>StringBuilder</code> you need to write something like this:</p> <pre><code>var sb = new StringBuilder(); sb.Append("&lt;a href='"); sb.Append(link); sb.Append("' class = '"); sb.Append(ccsClass); sb.Append("'/&gt;"); sb.ToString(); </code></pre> <p>It is not very cool, isn’t it? And compare how you can build it using <code>TagBuilder</code>;</p> <pre><code>var tb = new TagBuilder("a"); tb.MergeAttribute("href",link); tb.AddCssClass(cssClass); tb.ToString(TagRenderMode.SelfClosing); </code></pre> <p>Isn't that better?</p>
2,635,108
Running another ruby script from a ruby script
<p>In ruby, is it possible to specify to call another ruby script using the same ruby interpreter as the original script is being run by?</p> <p>For example, if a.rb runs b.rb a couple of times, is it possible to replace</p> <pre><code>system("ruby", "b.rb", "foo", "bar") </code></pre> <p>with something like</p> <pre><code>run_ruby("b.rb", "foo", "bar") </code></pre> <p>so that if you used <code>ruby1.9.1 a.rb</code> on the original, <code>ruby1.9.1</code> would be used on b.rb, but if you just used <code>ruby a.rb</code> on the original, <code>ruby</code> would be used on b.rb?</p> <p>I'd prefer not to use shebangs, as I'd like it to be able to run on different computers, some of which don't have <code>/usr/bin/env</code>.</p> <p><strong>Edit:</strong> I didn't mean <code>load</code> or <code>require</code> and the like, but spawning new processes (so I can use multiple CPUs).</p>
2,636,767
7
0
null
2010-04-14 05:38:14.813 UTC
12
2016-11-08 19:14:51.983 UTC
2010-04-14 05:54:57.973 UTC
null
38,765
null
38,765
null
1
38
ruby
48,384
<p><a href="http://Avdi.Org/devblog/" rel="noreferrer">Avdi Grimm</a> wrote a series of articles on the <a href="http://devver.wordpress.com/" rel="noreferrer">Devver blog</a> about different ways to start Ruby subprocesses last summer:</p> <ul> <li><a href="http://devver.wordpress.com/blog/2009/06/a-dozen-or-so-ways-to-start-sub-processes-in-ruby-part-1/" rel="noreferrer">A Dozen (or so) Ways to Start Subprocesses in Ruby: Part 1</a></li> <li><a href="http://devver.wordpress.com/blog/2009/07/a-dozen-or-so-ways-to-start-sub-processes-in-ruby-part-2/" rel="noreferrer">A Dozen (or so) Ways to Start Subprocesses in Ruby: Part 2</a></li> <li><a href="http://devver.wordpress.com/blog/2009/10/ruby-subprocesses-part_3/" rel="noreferrer">A Dozen (or so) Ways to Start Subprocesses in Ruby: Part 3</a></li> <li><a href="http://devver.wordpress.com/blog/2009/10/beware-of-pipe-duplication-in-subprocesses/" rel="noreferrer">Beware of pipe duplication in subprocesses</a></li> </ul> <p>[Note: it appears that part 4 hasn't been published yet.]</p>
2,626,262
Am I crazy? (How) should I create a jQuery content editor?
<p>Ok, so I created a CMS mainly aimed at Primary Schools. It's getting fairly popular in New Zealand but the one thing I hate with a passion is the largely bad quality of in browser WYSIWYG editors. I've been using KTML (made by InterAKT which was purchased by Adobe a few years ago). In my opinion this editor does a lot of great things (image editing/management, thumbnailing and pretty good content editing). Unfortunately time has had its nasty way with this product and new browsers are beginning to break features and generally degrade the performance of this tool. It's also quite scary basing my livelihood on a defunct product!</p> <p>I've been hunting, in fact I regularly hunt around to see if anything has changed in the WYSIWYG arena. The closest thing I've seen that excites me is the WYSIHAT framework, but they've decided to ignore a pretty relevant editing paradigm which I'm going to outline below. This is the idea for my proposed editor, and I don't know of any existing products that can do this properly:</p> <p>Right, so the traditional model for editing let's say a Page in a CMS is to log into a 'back end' and click edit on the page. This will then load another screen with the editor in it and perhaps a few other fields. More advanced CMS's will maybe have several editing boxes that are for different portions of the page. Anyway, the big problem with this way of doing things is that the user is editing a document outside of the final context it will appear in. In the simplest terms, this means the page template. Many things can be wrong, e.g. the with of the editing area might be different to the width of the actual template area. The height is nearly always fixed because existing editors always seem to use IFRAMES for backward compatibility. And there are plenty of other beefs which I'm sure you're quite aware of if you're in this development area.</p> <p>Here's my editor utopia:</p> <p>You click 'Edit Page': The actual page (with its actual template) displays. Portions of the page have been marked as editable via a class name. You click on one of these areas (in my case it'd just be the big 'body' area in the middle of the template) and a editing bar drops down from the top of the screen with all your standard controls (bold, italic, insert image etc...). Iframes are never used, instead we rely on setting contentEditable to true on the DIV's in question. Firefox 2 and IE6 can go away, let's move on. You can edit the page knowing exactly how it will look when you save it. Because all the styles for this template are loaded, your headings will look correct, everything will be just dandy. Is this such a radical concept? Why are we still content with TinyMCE and that other editor that is too embarrassing to use because it sounds like a swear word!?</p> <p>Let's face the facts:</p> <p>I'm a JavaScript novice. I did once play around in this area using the Javascript Anthology from SitePoint as a guide. It was quite a cool learning experience, but they of course used the IFRAME to make their lives easier. I tried to go a different route and just use contentEditable and even tried to sidestep the native content editing routines (execCommand) and instead wrote my own. They kind of worked but there were always issues.</p> <p>Now we have jQuery, and a few libraries that abstract things like IE's lack of Range support. I'm wondering, am I crazy, or is it actually a good idea to try and build an editor around this editing paradigm using jQuery and relevant plugins to make the job easier?</p> <p>My actual questions:</p> <ul> <li>Where would you start? </li> <li>What plugins do you know of that would help the most?</li> <li>Is it worth it, or is there a magical project that already exists that I should join in on? </li> <li>What are the biggest hurdles to overcome in a project like this? </li> <li>Am I crazy?</li> </ul> <p>I hope this question has been posted on the right board. I figured it is a technical question as I'm wanting to know specific hurdles and pitfalls to watch out for and also if it is technically feasible with todays technology.</p> <p>Looking forward to hearing peoples thoughts and opinions.</p> <p><strong>UPDATE</strong></p> <p>I've decided I will have a go at this and will start a github project for it when I have something cool to look at. From there I'd be totally happy for any help that people have to offer. It'll be open source of course :)</p> <p><strong>UPDATE 2</strong></p> <p>I've made the project and outlined the objectives. Let me know if you want to join the project group as a contributor, but I'll get the basics up first so there's something to start with.</p> <p>Here's the link: <a href="http://github.com/brendon/SpikeEdit" rel="noreferrer">http://github.com/brendon/SpikeEdit</a></p> <p><strong>Update 3</strong></p> <p>Wow! I've found this project. What a cool idea! I'm getting in touch with him to see if he ever got anywhere with it:</p> <p><a href="http://www.fluffy.co.uk/stediting" rel="noreferrer">http://www.fluffy.co.uk/stediting</a></p> <p><strong>Update 4</strong></p> <p>Ok, I got reasonably far. The biggest problems (like everyone always knows) is how to keep the code being generated in a reasonable state of affairs. WYSIHAT seems to have take on board the whole non-IFRAME thing, so I'm holding off to see how far that gets. They take the approach of just cleaning up the code at the end of the editing cycle. I think it should be cleaned on the fly otherwise you can edit yourself into a quagmire (I've done it a few times). When I have time I'll investigate some sort of homogenisation engine that could be plugged in to make the editing process behave as similarly as possible in all modern browsers.</p>
55,110,591
8
10
null
2010-04-13 00:21:39.103 UTC
13
2019-03-11 21:21:05.563 UTC
2010-06-28 03:17:18.813 UTC
null
129,798
null
129,798
null
1
32
jquery|editor|wysiwyg
4,118
<p>All these years later, I'm glad I didn't make my own! People have figured out that one can use <code>contenteditable</code> as an IO device to accept input then keep the actual HTML clean outside of the <code>contenteditable</code>. Two projects that I use that utilise this method are:</p> <ul> <li><a href="https://www.froala.com/wysiwyg-editor" rel="nofollow noreferrer">Froala Editor</a></li> <li><a href="https://trix-editor.org" rel="nofollow noreferrer">trix</a> (soon to be integrated into Ruby on Rails)</li> </ul> <p>Froala is by far and away the more feature-rich editor but they both operate in a similar way, leading to clean and predictable markup</p>
2,856,407
How to get access to raw resources that I put in res folder?
<p>In J2ME, I've do this like that: <code>getClass().getResourceAsStream("/raw_resources.dat");</code></p> <p>But in android, I always get null on this, why?</p>
2,859,721
8
2
null
2010-05-18 10:40:42.89 UTC
18
2020-12-20 00:26:39.32 UTC
2020-12-20 00:26:39.32 UTC
null
1,783,163
null
309,955
null
1
58
android|java-me|resources|inputstream|android-resources
128,884
<pre><code>InputStream raw = context.getAssets().open("filename.ext"); Reader is = new BufferedReader(new InputStreamReader(raw, "UTF8")); </code></pre>
2,668,909
How to find the real user home directory using python?
<p>I see that if we change the <code>HOME</code> (linux) or <code>USERPROFILE</code> (windows) environmental variable and run a python script, it returns the new value as the user home when I try</p> <pre><code>os.environ['HOME'] os.exp </code></pre> <p>Is there any way to find the real user home directory without relying on the environmental variable?</p> <p><strong>edit:</strong><br /> Here is a way to find userhome in windows by reading in the registry,<br /> <a href="http://mail.python.org/pipermail/python-win32/2008-January/006677.html" rel="nofollow noreferrer">http://mail.python.org/pipermail/python-win32/2008-January/006677.html</a></p> <p><strong>edit:</strong><br /> One way to find windows home using pywin32,</p> <pre><code>from win32com.shell import shell,shellcon home = shell.SHGetFolderPath(0, shellcon.CSIDL_PROFILE, None, 0) </code></pre>
2,668,952
9
3
null
2010-04-19 15:59:03 UTC
13
2022-01-24 07:58:38.753 UTC
2022-01-24 07:58:38.753 UTC
null
4,720,018
null
231,295
null
1
87
python|linux|windows|directory|home-directory
46,834
<p>I think <a href="http://docs.python.org/library/os.path.html#os.path.expanduser" rel="noreferrer"><code>os.path.expanduser(path)</code></a> could be helpful.</p> <blockquote> <p>On Unix and Windows, return the argument with an initial component of <code>~</code> or <code>~user</code> replaced by that user‘s home directory.</p> <p>On Unix, an initial <code>~</code> is replaced by the environment variable HOME if it is set; otherwise the current user’s home directory is looked up in the password directory through the built-in module <code>pwd</code>. <strong>An initial <code>~user</code> is looked up directly in the password directory</strong>.</p> <p>On Windows, HOME and USERPROFILE will be used if set, otherwise a <strong>combination of HOMEPATH and HOMEDRIVE</strong> will be used. <strong>An initial <code>~user</code> is handled by stripping the last directory component from the created user path derived above</strong>.</p> <p>If the expansion fails or if the path does not begin with a tilde, the path is returned unchanged.</p> </blockquote> <p>So you could just do:</p> <pre><code>os.path.expanduser('~user') </code></pre>
2,604,869
Finding the Eclipse Version Number
<p>I have posted how to find it in Eclipse Gallileo, but if anyone has information on older versions feel free to post it below.</p>
2,605,648
11
1
null
2010-04-09 03:02:48.497 UTC
18
2021-10-07 07:31:08.86 UTC
2010-04-09 03:15:28.8 UTC
null
165,495
null
165,495
null
1
117
eclipse|version
109,242
<p>(Update September 2012):</p> <p><a href="https://stackoverflow.com/users/1132117/mrt">MRT</a> points out <a href="https://stackoverflow.com/questions/2604869/finding-the-eclipse-version-number/2605648#comment16777920_2605648">in the comments</a> that "<a href="https://stackoverflow.com/questions/2313660/eclipse-version">Eclipse Version</a>" question references a <code>.eclipseproduct</code> in the main folder, and it contains:</p> <pre><code>name=Eclipse Platform id=org.eclipse.platform version=3.x.0 </code></pre> <p>So that seems more straightforward than my original answer below.</p> <p>Also, <a href="https://stackoverflow.com/users/74694/neeme-praks">Neeme Praks</a> mentions <a href="https://stackoverflow.com/a/28557539/6309">below</a> that there is a <code>eclipse/configuration/config.ini</code> which includes a line like:</p> <pre><code>eclipse.buildId=4.4.1.M20140925-0400 </code></pre> <p>Again easier to find, as those are Java properties set and found with <code>System.getProperty("eclipse.buildId")</code>.</p> <hr> <p>Original answer (April 2009)</p> <p>For Eclipse Helios 3.6, you can deduce the Eclipse Platform version directly from the About screen:<br> It is a combination of the Eclipse global version and the build Id:</p> <p><img src="https://i.stack.imgur.com/wzFyS.png" alt="alt text"></p> <p>Here is an example for Eclipse 3.6M6:<br> The version would be: <strong>3.6.0.v201003121448</strong>, after the version 3.6.0 and the build Id I20100312-1448 (an Integration build from March 12th, 2010 at 14h48</p> <p>To see it more easily, click on "Plugin Details" and sort by Version.</p> <hr> <p>Note: Eclipse3.6 has a brand new cool logo:</p> <p><img src="https://i.stack.imgur.com/ZVeYo.png" alt="alt text"></p> <p>And you can see the build Id now being displayed during the loading step of the different plugin.</p>
2,781,357
File being used by another process after using File.Create()
<p>I'm trying to detect if a file exists at runtime, if not, create it. However I'm getting this error when I try to write to it: </p> <blockquote> <p>The process cannot access the file 'myfile.ext' because it is being used by another process.</p> </blockquote> <pre><code>string filePath = string.Format(@"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); if (!File.Exists(filePath)) { File.Create(filePath); } using (StreamWriter sw = File.AppendText(filePath)) { //write my text } </code></pre> <p>Any ideas on how to fix it?</p>
2,781,509
11
0
null
2010-05-06 13:15:50.02 UTC
15
2022-07-03 17:45:19.33 UTC
2014-06-17 07:19:32.23 UTC
null
505,893
null
329,746
null
1
134
c#|file-io
197,082
<p>The <code>File.Create</code> method creates the file and opens a <code>FileStream</code> on the file. So your file is already open. You don't really need the file.Create method at all:</p> <pre><code>string filePath = @"c:\somefilename.txt"; using (StreamWriter sw = new StreamWriter(filePath, true)) { //write to the file } </code></pre> <p>The boolean in the <code>StreamWriter</code> constructor will cause the contents to be appended if the file exists.</p>
2,882,551
Can knowing C actually hurt the code you write in higher level languages?
<p>The question seems settled, beaten to death even. Smart people have said <a href="http://www.joelonsoftware.com/articles/fog0000000319.html" rel="nofollow noreferrer">smart things</a> on the subject. To be a really good programmer, <a href="https://stackoverflow.com/questions/296/should-i-learn-c">you need to know C</a>.</p> <p>Or do you?</p> <p>I was enlightened twice this week. <a href="https://serverfault.com/questions/23621/any-benefit-or-detriment-from-removing-a-pagefile-on-an-8gb-ram-machine">The first one</a> made me realize that my assumptions don't go further than my knowledge behind them, and given the complexity of software running on my machine, that's almost non-existent. But what really drove it home was <a href="http://slashdot.org/comments.pl?sid=1650374&amp;cid=32193298" rel="nofollow noreferrer">this Slashdot comment</a>:</p> <blockquote>The end result is that I notice the many naive ways in which traditional C "bare metal" programmers assume that higher level languages are implemented. They make bad "optimization" decisions in projects they influence, because they have no idea how a compiler works or how different a good runtime system may be from the naive macro-assembler model they understand.</blockquote> <p>Then it hit me: C is just <a href="http://www.joelonsoftware.com/articles/LeakyAbstractions.html" rel="nofollow noreferrer">one more abstraction</a>, like all others. Even <a href="http://en.wikipedia.org/wiki/Microarchitecture#Microarchitectural_concepts" rel="nofollow noreferrer">the CPU itself</a> is only an abstraction! I've just never seen it break, because I don't have the tools to measure it.</p> <p>I'm confused. Has my mind been mutilated beyond recovery, like Dijkstra said about BASIC? Am I living in a constant state of premature optimization? Is there hope for me, now that I realized I know nothing about anything? Is there anything to know, even? And why is it so fascinating, that everything I've written in the last five years might have been fundamentally wrong?</p> <p>To sum it up: is there any value in knowing more than the API docs tell me?</p> <p>EDIT: Made CW. Of course this also means now you must post examples of the interpreter/runtime optimizing better than we do :)</p>
2,882,742
19
7
2010-05-21 13:52:52.833 UTC
2010-05-21 13:44:19.593 UTC
9
2010-05-27 22:58:04.97 UTC
2017-05-23 12:09:50.057 UTC
null
-1
null
127,007
null
1
35
c|language-agnostic|optimization|premature-optimization
2,041
<p>Neither knowing C nor knowing the lower-level details of implementation hurt you -- in themselves. What can and will hurt you is if you consistently think and work in terms of the low-level details, even when it's inappropriate.</p> <p>The old saying was that "real programmers can write FORTRAN in <em>any</em> language." If you do the same using C, it's not an improvement. If you're writing Lisp, write Lisp. If you're writing Python, write Python. What's appropriate and reasonable for C is not for either of those (or any of many others).</p> <p>A great programmer needs to be able to think at many different levels of abstraction, and (more importantly) recognize and apply the level of abstraction that's appropriate to the task at hand.</p> <p>Knowledge of C's level of abstraction doesn't hurt. Ignorance of alternatives can (and will).</p>
2,816,715
Branch from a previous commit using Git
<p>If I have <code>N</code> commits, how do I branch from the <code>N-3</code> commit?</p>
2,816,728
21
0
null
2010-05-12 07:21:55.753 UTC
450
2022-07-25 02:40:56.297 UTC
2022-07-25 02:37:30.557 UTC
null
365,102
null
86,112
null
1
2,365
git|branch|git-branch
997,872
<p>Create the branch using a commit hash:</p> <pre><code>git branch branch_name &lt;commit-hash&gt; </code></pre> <p>Or by using a symbolic reference:</p> <pre><code>git branch branch_name HEAD~3 </code></pre> <p>To checkout the branch while creating it, use:</p> <pre><code>git checkout -b branch_name &lt;commit-hash or HEAD~3&gt; </code></pre>
25,119,193
Matplotlib pyplot axes formatter
<p>I have an image: </p> <p><img src="https://i.stack.imgur.com/6Xuwb.png" alt="enter image description here"></p> <p>Here in the y-axis I would like to get <code>5x10^-5 4x10^-5</code> and so on instead of <code>0.00005 0.00004</code>. </p> <p>What I have tried so far is: </p> <pre><code>fig = plt.figure() ax = fig.add_subplot(111) y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=True) ax.yaxis.set_major_formatter(y_formatter) ax.plot(m_plot,densities1,'-ro',label='0.0&lt;z&lt;0.5') ax.plot(m_plot,densities2, '-bo',label='0.5&lt;z&lt;1.0') ax.legend(loc='best',scatterpoints=1) plt.legend() plt.show() </code></pre> <p>This does not seem to work. The <a href="http://matplotlib.org/api/ticker_api.html">document page</a> for tickers does not seem to provide a direct answer. </p>
25,119,872
1
0
null
2014-08-04 12:55:23.27 UTC
1
2014-08-04 13:30:12.543 UTC
null
null
null
null
3,397,243
null
1
12
python|matplotlib|axes|ticker
45,279
<p>You can use <a href="http://matplotlib.org/api/ticker_api.html#matplotlib.ticker.FuncFormatter" rel="noreferrer"><code>matplotlib.ticker.FuncFormatter</code></a> to choose the format of your ticks with a function as shown in the example code below. Effectively all the function is doing is converting the input (a float) into exponential notation and then replacing the 'e' with 'x10^' so you get the format that you want.</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.ticker as tick import numpy as np x = np.linspace(0, 10, 1000) y = 0.000001*np.sin(10*x) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, y) def y_fmt(x, y): return '{:2.2e}'.format(x).replace('e', 'x10^') ax.yaxis.set_major_formatter(tick.FuncFormatter(y_fmt)) plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/oPSph.png" alt="image"></p> <p>If you're willing to use exponential notation (i.e. 5.0e-6.0) however then there is a much tidier solution where you use <a href="http://matplotlib.org/api/ticker_api.html#matplotlib.ticker.FormatStrFormatter" rel="noreferrer"><code>matplotlib.ticker.FormatStrFormatter</code></a> to choose a format string as shown below. The string format is given by the standard Python string formatting rules.</p> <pre><code>... y_fmt = tick.FormatStrFormatter('%2.2e') ax.yaxis.set_major_formatter(y_fmt) ... </code></pre>
23,654,168
How to query the default include paths of clang++?
<p>How can I query the default include path of clang/clang++? I am trying to use a custom built clang compiler (the one that supports OpenMP), but it doesn't seem to find the STL libraries: </p> <pre><code>/usr/local/bin/clang++ hello.cpp hello.cpp:1:10: fatal error: 'iostream' file not found #include &lt;iostream&gt; ^ 1 error generated. </code></pre> <p>By using an IDE, back-tracking the #include iostream, and finally using the <strong>-isystem</strong> option I got the simple helloworld application to compile in OSX 10.9:</p> <pre><code>/usr/local/bin/clang++ -isystem /Library/Developer/CommandLineTools/usr/lib/c++/v1 hello.cpp </code></pre> <p>Thanks for your help!</p>
23,658,940
2
0
null
2014-05-14 12:01:18.41 UTC
1
2021-07-31 19:51:09.493 UTC
null
null
null
null
2,202,787
null
1
31
c++|clang
28,043
<p>You are looking for option <code>-v</code>. Compiling with <code>clang++ -c file.cc -v</code> will print among other things:</p> <pre><code>#include "..." search starts here: #include &lt;...&gt; search starts here: /usr/bin/../lib/gcc/x86_64-linux-gnu/4.9/../../../../include/c++/4.9 </code></pre> <p>etc.</p>
40,161,516
How do you programmatically update query params in react-router?
<p>I can't seem to find how to update query params with react-router without using <code>&lt;Link/&gt;</code>. <code>hashHistory.push(url)</code> doesn't seem to register query params, and it doesn't seem like you can pass a query object or anything as a second argument.</p> <p>How do you change the url from <code>/shop/Clothes/dresses</code> to <code>/shop/Clothes/dresses?color=blue</code> in react-router without using <code>&lt;Link&gt;</code>? </p> <p>And is an <code>onChange</code> function really the only way to listen for query changes? Why aren't query changes automatically detected and reacted-to the way that param changes are?</p>
40,161,954
16
1
null
2016-10-20 18:06:09.1 UTC
30
2022-08-02 10:47:42.117 UTC
2018-09-12 00:03:43.39 UTC
null
6,368,697
null
3,745,986
null
1
220
reactjs|react-router
333,865
<p>Within the <code>push</code> method of <code>hashHistory</code>, you can specify your query parameters. For instance, </p> <pre><code>history.push({ pathname: '/dresses', search: '?color=blue' }) </code></pre> <p>or</p> <pre><code>history.push('/dresses?color=blue') </code></pre> <p>You can check out this <a href="https://github.com/mjackson/history" rel="noreferrer">repository</a> for additional examples on using <code>history</code></p>
10,402,197
How to create the linked server for SQL Server 2008 where we have the database from 2000 and 2005
<p>Currently I am working on SQL Server 2000,2005 &amp; 2008, my requirement is like, the database available in SQL Server 2000 &amp; 2005 will be available in 2008 using a linked server.</p> <p>Let's say I have a database in SQL Server 2000 called <code>LIVE_2000</code> and in SQL Server 2005 it's called <code>LIVE_2005</code>, can someone please help me to create the linked server for <code>LIVE_2000</code> and <code>LIVE_2005</code> into SQL Server 2008?</p> <p>1st thing is this even possible?</p> <p>Thanks in advance...`</p>
10,402,764
1
0
null
2012-05-01 18:17:52.743 UTC
12
2022-04-18 15:26:20.913 UTC
2012-05-01 21:18:19.453 UTC
null
13,302
null
1,004,164
null
1
10
sql-server|sql-server-2008|sql-server-2005|sql-server-2000
71,645
<p>There are a <a href="http://www.c-sharpcorner.com/uploadfile/suthish_nair/linked-servers-in-sql-server-2008/" rel="noreferrer">few different ways</a> that you can create a linked server in SQL Server you can use the GUI in SQL Server Management Studio or via a script.</p> <p>Using the <a href="http://msdn.microsoft.com/en-us/library/aa560998%28v=bts.10%29.aspx" rel="noreferrer">instructions on MSDN</a> you can do the following:</p> <blockquote> <ol> <li><p>Click Start, click All Programs, click Microsoft SQL Server 2005 or Microsoft SQL Server 2008, and then click SQL Server Management Studio.</p></li> <li><p>In the Connect to Server dialog box, specify the name of the appropriate SQL Server, and then click Connect.</p></li> <li><p>In SQL Server Management Studio, double-click Server Objects, right-click Linked Servers, and then click New Linked Server.</p></li> <li><p>In the New Linked Server dialog box, on the General page, in Linked server, enter the full network name of the SQL Serveryou want to link to.</p></li> <li><p>Under Server type, click SQL Server.</p></li> <li><p>In the left pane of the New Linked Server dialog, under Select a page, choose Security.</p></li> <li><p>You will need to map a local server login to a remote server login. On the right side of the Security page, click the Add button.</p></li> <li><p>Under Local Login, select a local login account to connect to the remote server. Check Impersonate if the local login also exists on the remote server. Alternatively, if the local login will be mapped to a remote SQL Server login you must supply the Remote User name and Remote Password for the remote server login.</p></li> <li><p>In the left pane of the New Linked Server dialog, under Select a page, choose Server Options. Set the Rpc and Rpc Out parameters to True, and then click OK.</p></li> </ol> </blockquote> <p>An alternate way would be to use Transact SQL to write the query to set up the server using the stored procedure <a href="http://technet.microsoft.com/en-us/library/ms190479%28v=sql.100%29.aspx" rel="noreferrer"><code>sp_addlinkedserver</code></a></p> <pre><code>EXEC sp_addlinkedserver @server='yourServer', @srvproduct='', @provider='SQLNCLI', @datasrc='yourServer\instance1'; </code></pre> <p>Either version will set up the linked server that you can then reference in your code. </p>
10,330,342
Threejs: assign different colors to each vertex in a geometry
<p>I want to do picking via IdMapping in Three.js</p> <p>Because of performance issues I only have one huge geometry, computed like this:</p> <pre><code>for (var i = 0; i &lt; numberOfVertices; i += 9) { p1 = new THREE.Vector3(graphData.triangles.vertices[i+0], graphData.triangles.vertices[i+1], graphData.triangles.vertices[i+2]); p2 = new THREE.Vector3(graphData.triangles.vertices[i+3], graphData.triangles.vertices[i+4], graphData.triangles.vertices[i+5]); p3 = new THREE.Vector3(graphData.triangles.vertices[i+6], graphData.triangles.vertices[i+7], graphData.triangles.vertices[i+8]); geometry.vertices.push(new THREE.Vertex( p1.clone() )); geometry.vertices.push(new THREE.Vertex( p2.clone() )); geometry.vertices.push(new THREE.Vertex( p3.clone() )); geometry.faces.push( new THREE.Face3( i/3, i/3+1, i/3+2 ) ); // i want to do something like this: geometry.colors.push(new THREE.Color(0xFF0000)); geometry.colors.push(new THREE.Color(0xFF0000)); geometry.colors.push(new THREE.Color(0xFF0000)); } geometry.computeFaceNormals(); var material = new THREE.MeshBasicMaterial({}); var triangles = new THREE.Mesh( geometry, material ); scene.add(triangles); </code></pre> <p>How can I assign different colors to each vertex in my geometry?</p>
10,332,518
3
0
null
2012-04-26 09:05:57.597 UTC
7
2015-08-07 22:35:29.99 UTC
2012-09-27 21:13:07.753 UTC
null
344,480
null
1,152,174
null
1
21
javascript|webgl|three.js|picking
38,700
<p>It has to be geometry.vertexColors instead of geometry.colors (push a colour per vertex).</p> <p>And the material:</p> <pre><code>material = new THREE.MeshBasicMaterial({ vertexColors: THREE.VertexColors }); </code></pre>
10,569,165
How to map "jj" to Esc in emacs Evil mode
<p>Recently I tried Emacs and found Evil helpful to keep my vim custom. I'm used to typing "jj" to return normal mode from insert mode like many Vimers do but don't know how to make it in Evil mode.</p> <p>I map it like this but seems not correct:</p> <pre><code>(define-key evil-insert-state-map (kbd "jj") 'evil-normal-state) </code></pre>
13,543,550
8
0
null
2012-05-13 03:40:03.377 UTC
12
2022-04-15 06:45:27.793 UTC
null
null
null
null
962,163
null
1
49
emacs|evil-mode
18,233
<p>This works for me. It requires the <a href="http://emacswiki.org/emacs/KeyChord">KeyChord</a> library:</p> <pre class="lang-el prettyprint-override"><code>;;Exit insert mode by pressing j and then j quickly (setq key-chord-two-keys-delay 0.5) (key-chord-define evil-insert-state-map "jj" 'evil-normal-state) (key-chord-mode 1) </code></pre> <p>It is inspired by @phils answer above and based on <a href="http://bbbscarter.wordpress.com/2012/09/13/emacs-bits-and-bobs/">Simon's Coding Blog: Emacs and Unity Every Day</a>.</p>
6,136,588
Image Cropping using Python
<p>I am new to Python coding and I am writing a program in which I will be cropping an entered image and then saving it in a location. Now, I am being able to do this using a combination of PIL and pygame. But the problem is that, when I am selecting the image from the open pygame window, the selection area is totally opaque and I am not able to see through the region I am selecting. This is causing problems for my boss who wants to be able to see through it as he selects. For you guys to better understand the problem, I am writing my code here:</p> <pre><code>import pygame, sys from PIL import Image pygame.init() def displayImage( screen, px, topleft): screen.blit(px, px.get_rect()) if topleft: pygame.draw.rect( screen, (128,128,128), pygame.Rect(topleft[0], topleft[1], pygame.mouse.get_pos()[0] - topleft[0], pygame.mouse.get_pos()[1] - topleft[1])) pygame.display.flip() def setup(path): px = pygame.image.load(path) screen = pygame.display.set_mode( px.get_rect()[2:] ) screen.blit(px, px.get_rect()) pygame.display.flip() return screen, px def mainLoop(screen, px): topleft = None bottomright = None n=0 while n!=1: for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONUP: if not topleft: topleft = event.pos else: bottomright = event.pos n=1 displayImage(screen, px, topleft) return ( topleft + bottomright ) if __name__ == "__main__": input_loc="C:\pic1.PNG" output_loc="C:\pic2.PNG" screen, px = setup(input_loc) left, upper, right, lower = mainLoop(screen, px) im = Image.open(input_loc) im = im.crop(( left, upper, right, lower)) pygame.display.quit() im.save(output_loc) </code></pre> <p>Any help is appreciated. Regards.</p>
6,140,013
2
0
null
2011-05-26 09:44:24.523 UTC
9
2013-07-04 11:55:54.127 UTC
2013-07-04 11:55:54.127 UTC
null
569,101
null
754,398
null
1
9
python|image-processing|python-imaging-library|crop
15,187
<p>I took a quick look and fixed a few other problems along the way. Essentially my changes do this:</p> <ul> <li>Draw the bounding box on a temporary image, set its alpha transparency, and then blit this over top of the main image.</li> <li>Avoid extraneous drawing cycles (when the mouse isn't moving, no sense in drawing the same image again).</li> <li>Ensure that width and height are always positive. If the rect is drawn by dragging the mouse left or up, your code would end up with a negative width and/or height, raising an exception when trying to write the final image.</li> </ul> <p>Here is a screenshot of running the fixed code:</p> <p><img src="https://i.stack.imgur.com/OLOO2.png" alt="enter image description here"></p> <p>I split the code into two parts to avoid the scrollbars:</p> <pre><code>import pygame, sys from PIL import Image pygame.init() def displayImage(screen, px, topleft, prior): # ensure that the rect always has positive width, height x, y = topleft width = pygame.mouse.get_pos()[0] - topleft[0] height = pygame.mouse.get_pos()[1] - topleft[1] if width &lt; 0: x += width width = abs(width) if height &lt; 0: y += height height = abs(height) # eliminate redundant drawing cycles (when mouse isn't moving) current = x, y, width, height if not (width and height): return current if current == prior: return current # draw transparent box and blit it onto canvas screen.blit(px, px.get_rect()) im = pygame.Surface((width, height)) im.fill((128, 128, 128)) pygame.draw.rect(im, (32, 32, 32), im.get_rect(), 1) im.set_alpha(128) screen.blit(im, (x, y)) pygame.display.flip() # return current box extents return (x, y, width, height) </code></pre> <p>And part 2 (concatenate to the above):</p> <pre><code>def setup(path): px = pygame.image.load(path) screen = pygame.display.set_mode( px.get_rect()[2:] ) screen.blit(px, px.get_rect()) pygame.display.flip() return screen, px def mainLoop(screen, px): topleft = bottomright = prior = None n=0 while n!=1: for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONUP: if not topleft: topleft = event.pos else: bottomright = event.pos n=1 if topleft: prior = displayImage(screen, px, topleft, prior) return ( topleft + bottomright ) if __name__ == "__main__": input_loc = 'stack.png' output_loc = 'out.png' screen, px = setup(input_loc) left, upper, right, lower = mainLoop(screen, px) # ensure output rect always has positive width, height if right &lt; left: left, right = right, left if lower &lt; upper: lower, upper = upper, lower im = Image.open(input_loc) im = im.crop(( left, upper, right, lower)) pygame.display.quit() im.save(output_loc) </code></pre>
31,414,263
Python using open (w+) FileNotFoundError
<p>I get a <code>FileNotFoundError</code> when trying to write to a file. This is my code:</p> <pre><code>def save_txt_individual_tracks(track, folder, i): f = open(folder+str(i)+'.txt','w+') for line in track: l=str(line[0])+','+str(line[1])+','+str(line[2])+'\n' f.write(l) f.close() </code></pre> <p>Which I call like so:</p> <pre><code>save_txt_individual_tracks(new,'E:/phoneTracks/'+track_name+'/',i) </code></pre> <p>Which gives me this error:</p> <blockquote> <p>FileNotFoundError: [Errno 2] No such file or directory: 'E:/phoneTracks/TA92903URN7ff/0.txt'</p> </blockquote> <p>I created folder <code>phoneTracks</code> in E. And I am confused about <code>open()</code> with mode <code>'w+'</code>, which is used to create a new file. Why do I get a <code>FileNotFoundError</code>? What can I do to fix it?</p> <p>I am running python3.4.3 on windows 7</p>
31,414,405
1
2
null
2015-07-14 18:15:48.283 UTC
3
2022-07-08 11:59:41.013 UTC
2022-07-08 11:59:11.563 UTC
null
4,298,200
null
5,106,470
null
1
21
python
44,318
<p>You are getting the error because the directory - <code>E:/phoneTracks/TA92903URN7ff/</code> does not exist.</p> <p>Example to show this error -</p> <pre><code>In [57]: open('blah/abcd.txt','w+') --------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) &lt;ipython-input-57-46a07d4a5d18&gt; in &lt;module&gt;() ----&gt; 1 open('blah/abcd.txt','w+') FileNotFoundError: [Errno 2] No such file or directory: 'blah/abcd.txt' </code></pre> <p>Got error in my code, because the directory <code>blah/</code> does not exist.</p> <p>If the directory - <code>TA92903URN7ff/</code> is constant, try creating it and then running. If its not constant, you can checkout <a href="https://docs.python.org/2/library/os.path.html#os.path.exists" rel="nofollow noreferrer"><code>os.path.exists</code></a> to check if the directory exists or not, and if it doesn't exist, create one using <a href="https://docs.python.org/2/library/os.html#os.mkdir" rel="nofollow noreferrer"><code>os.mkdir</code></a> .</p> <p>Example -</p> <pre><code>import os, os.path def save_txt_individual_tracks(track,folder,i): if not os.path.exists(folder): os.mkdir(folder) elif not os.path.isdir(folder): return #you may want to throw some error or so. f = open(os.path.join(folder, str(i)+'.txt'),'w+') for line in track: l=str(line[0])+','+str(line[1])+','+str(line[2])+'\n' f.write(l) f.close() </code></pre> <p>Also, you should consider using <code>os.path.join</code> to join paths, instead of using string concatenation. And also using <code>with</code> statement for openning files as - <code>with open(os.path.join(folder, str(i)+'.txt'),'w+') as f:</code> , that way the file will automatically get closed once the <code>with</code> block ends.</p>
23,018,985
Python cProfile results: two numbers for ncalls
<p>I just recently began profiling a server application that I've been working on, trying to find out where some excess processor time is being spent and looking for ways to make things smoother.</p> <p>Overall, I think I've got a good hang of using cProfile and pstats, but I don't understand how some of functions list two numbers in the ncalls column.</p> <p>For example, in the below results, why are there two numbers listed for all the copy.deepcopy stuff?</p> <pre><code> 2892482 function calls (2476782 primitive calls) in 5.952 seconds Ordered by: cumulative time ncalls tottime percall cumtime percall filename:lineno(function) 27 0.015 0.001 5.229 0.194 /usr/local/lib/python2.7/twisted/internet/base.py:762(runUntilCurrent) 7 0.000 0.000 3.109 0.444 /usr/local/lib/python2.7/twisted/internet/task.py:201(__call__) 7 0.000 0.000 3.109 0.444 /usr/local/lib/python2.7/twisted/internet/defer.py:113(maybeDeferred) 5 0.000 0.000 2.885 0.577 defs/1sec.def:3690(onesec) 5 2.100 0.420 2.885 0.577 defs/1sec.def:87(loop) 1523 0.579 0.000 2.105 0.001 defs/cactions.def:2(cActions) 384463/1724 0.474 0.000 1.039 0.001 /usr/local/lib/python2.7/copy.py:145(deepcopy) 33208/1804 0.147 0.000 1.018 0.001 /usr/local/lib/python2.7/copy.py:226(_deepcopy_list) 17328/15780 0.105 0.000 0.959 0.000 /usr/local/lib/python2.7/copy.py:253(_deepcopy_dict) </code></pre>
23,019,605
1
0
null
2014-04-11 17:28:50.437 UTC
4
2020-08-07 19:41:48.467 UTC
null
null
null
null
2,030,232
null
1
30
python|cprofile
5,530
<p>The smaller number is the number of 'primitive' or non-recursive calls. The larger number is the total number of invocations, including recursive calls. Since deepcopy is implemented recursively, it means that you called deepcopy directly 1724 times, but that it ended up calling itself ~383k times to copy sub-objects.</p>
47,220,595
Why the 6 in relu6?
<p>I've hacked a deep feed forward NN from scratch in R, and it seems more stable with "hard sigmoid" activations - max(0,min(1,x)) - than ReLU. Trying to port it to TensorFlow, and noticed that they don't have this activation function built in, only relu6, which uses an upper cutoff at 6. Is there a reason for this? (I realize that you could do relu6(x*6)/6, but if the TF guys put the 6 there for a good reason, I'd like to know.) Also, I'd like to know if others have explosion problems with ReLU in feed forward nets (I'm aware of RNN issues).</p>
47,220,765
3
0
null
2017-11-10 10:25:06.283 UTC
11
2020-10-02 16:45:17.037 UTC
null
null
null
null
8,918,908
null
1
66
tensorflow
33,711
<p>From <a href="https://www.reddit.com/r/MachineLearning/comments/3s65x8/tensorflow_relu6_minmaxfeatures_0_6/" rel="noreferrer">this reddit thread</a>:</p> <blockquote> <p>This is useful in making the networks ready for fixed-point inference. If you unbound the upper limit, you lose too many bits to the Q part of a Q.f number. Keeping the ReLUs bounded by 6 will let them take a max of 3 bits (upto 8) leaving 4/5 bits for .f</p> </blockquote> <p>It seems, then, that 6 is just an arbitrary value chosen according to the number of bits you want to be able to compress your network's trained parameters into. As per the "why" only the version with value 6 is implemented, I assume it's because that's the value that fits best in 8 bits, which probably is the most common use-case.</p>
21,524,642
Splitting string with pipe character ("|")
<p>I'm not able to split values from this string: </p> <p><code>"Food 1 | Service 3 | Atmosphere 3 | Value for money 1 "</code></p> <p>Here's my current code:</p> <pre><code>String rat_values = "Food 1 | Service 3 | Atmosphere 3 | Value for money 1 "; String[] value_split = rat_values.split("|"); </code></pre> <h3>Output</h3> <blockquote> <p>[, F, o, o, d, , 1, , |, , S, e, r, v, i, c, e, , 3, , |, , A, t, m, o, s, p, h, e, r, e, , 3, , |, , V, a, l, u, e, , f, o, r, , m, o, n, e, y, , 1, ]</p> </blockquote> <h3>Expected output</h3> <blockquote> <p>Food 1<br> Service 3<br> Atmosphere 3<br> Value for money 1</p> </blockquote>
21,524,670
5
0
null
2014-02-03 10:19:02.73 UTC
42
2016-04-27 16:32:02.033 UTC
2014-02-03 10:22:13.143 UTC
null
474,189
null
1,872,067
null
1
293
java|regex
281,785
<p><code>|</code> is a metacharacter in regex. You'd need to escape it:</p> <pre><code>String[] value_split = rat_values.split("\\|"); </code></pre>
36,880,321
Why redis can not set maximum open file
<pre> 1167:M 26 Apr 13:00:34.666 # You requested maxclients of 10000 requiring at least 10032 max file descriptors. 1167:M 26 Apr 13:00:34.667 # Redis can't set maximum open files to 10032 because of OS error: Operation not permitted. 1167:M 26 Apr 13:00:34.667 # Current maximum open files is 4096. maxclients has been reduced to 4064 to compensate for low ulimit. If you need higher maxclients increase 'ulimit -n'. 1167:M 26 Apr 13:00:34.685 # Creating Server TCP listening socket 192.34.62.56​​:6379: Name or service not known 1135:M 26 Apr 20:34:24.308 # You requested maxclients of 10000 requiring at least 10032 max file descriptors. 1135:M 26 Apr 20:34:24.309 # Redis can't set maximum open files to 10032 because of OS error: Operation not permitted. 1135:M 26 Apr 20:34:24.309 # Current maximum open files is 4096. maxclients has been reduced to 4064 to compensate for low ulimit. If you need higher maxclients increase 'ulimit -n'. 1135:M 26 Apr 20:34:24.330 # Creating Server TCP listening socket 192.34.62.56​​:6379: Name or service not known </pre>
36,880,362
3
0
null
2016-04-27 04:28:05.387 UTC
10
2018-07-17 20:32:33.187 UTC
2018-07-17 20:32:33.187 UTC
null
3,309,030
null
3,686,582
null
1
23
redis
40,942
<p>Redis will never change the maximum open files.</p> <p>This is a OS configuration and it can be configured on a per user basis also. The error is descriptive and tells you: "increase 'ulimit -n'"</p> <p>You can refer to this blog post on how to increase the maximum open files descriptors: <a href="http://www.cyberciti.biz/faq/linux-increase-the-maximum-number-of-open-files/" rel="noreferrer">http://www.cyberciti.biz/faq/linux-increase-the-maximum-number-of-open-files/</a></p>
30,085,063
Take a screenshot of RecyclerView in FULL length
<p>I want to get a "full page" screenshot of the activity. The view contains a RecyclerView with many items.</p> <p>I can take a screenshot of the current view with this function:</p> <pre><code>public Bitmap getScreenBitmap() { View v= findViewById(R.id.container).getRootView(); v.setDrawingCacheEnabled(true); v.buildDrawingCache(true); Bitmap b = Bitmap.createBitmap(v.getDrawingCache()); v.setDrawingCacheEnabled(false); // clear drawing cache return b; } </code></pre> <p>But it contains only the items I can view normally (as expected).</p> <p><strong>Is there some way to make the RecyclerView magically show in full length (display all items at once) when I take the screenshot?</strong></p> <p>If not, how should I approach this problem?</p>
31,017,673
5
1
null
2015-05-06 18:43:45.527 UTC
13
2020-09-22 18:02:11.85 UTC
null
null
null
null
416,319
null
1
11
java|android
10,329
<p>Inspired from Yoav's answer. This code works for recyclerview item types and probably regardless of it's size. </p> <p>It was tested with a recyclerview having linearlayout manager and three item types. Yet to check it with other layout managers.</p> <pre><code>public Bitmap getScreenshotFromRecyclerView(RecyclerView view) { RecyclerView.Adapter adapter = view.getAdapter(); Bitmap bigBitmap = null; if (adapter != null) { int size = adapter.getItemCount(); int height = 0; Paint paint = new Paint(); int iHeight = 0; final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // Use 1/8th of the available memory for this memory cache. final int cacheSize = maxMemory / 8; LruCache&lt;String, Bitmap&gt; bitmaCache = new LruCache&lt;&gt;(cacheSize); for (int i = 0; i &lt; size; i++) { RecyclerView.ViewHolder holder = adapter.createViewHolder(view, adapter.getItemViewType(i)); adapter.onBindViewHolder(holder, i); holder.itemView.measure(View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); holder.itemView.layout(0, 0, holder.itemView.getMeasuredWidth(), holder.itemView.getMeasuredHeight()); holder.itemView.setDrawingCacheEnabled(true); holder.itemView.buildDrawingCache(); Bitmap drawingCache = holder.itemView.getDrawingCache(); if (drawingCache != null) { bitmaCache.put(String.valueOf(i), drawingCache); } // holder.itemView.setDrawingCacheEnabled(false); // holder.itemView.destroyDrawingCache(); height += holder.itemView.getMeasuredHeight(); } bigBitmap = Bitmap.createBitmap(view.getMeasuredWidth(), height, Bitmap.Config.ARGB_8888); Canvas bigCanvas = new Canvas(bigBitmap); bigCanvas.drawColor(Color.WHITE); for (int i = 0; i &lt; size; i++) { Bitmap bitmap = bitmaCache.get(String.valueOf(i)); bigCanvas.drawBitmap(bitmap, 0f, iHeight, paint); iHeight += bitmap.getHeight(); bitmap.recycle(); } } return bigBitmap; } </code></pre>
28,348,879
Only variable references should be returned by reference - Codeigniter
<p>After the server PHP upgrade I am getting the following error with PHP Version 5.6.2 on Apache 2.0</p> <pre><code>A PHP Error was encountered Severity: Notice Message: Only variable references should be returned by reference Filename: core/Common.php Line Number: 257 </code></pre> <p>How can I fix this?</p>
28,348,880
3
0
null
2015-02-05 16:17:51.02 UTC
44
2019-11-16 04:57:13.007 UTC
2015-06-04 10:31:49.743 UTC
null
1,263,783
null
1,263,783
null
1
179
php|apache|codeigniter|apache2|codeigniter-2
307,395
<p>Edit filename: core/Common.php, line number: 257</p> <p>Before</p> <pre><code>return $_config[0] =&amp; $config; </code></pre> <p>After</p> <pre><code>$_config[0] =&amp; $config; return $_config[0]; </code></pre> <h1>Update</h1> <p>Added by NikiC</p> <p>In PHP assignment expressions always return the assigned value. So $_config[0] =&amp; $config returns $config - but not the variable itself, but a copy of its value. And returning a reference to a temporary value wouldn't be particularly useful (changing it wouldn't do anything).</p> <h2>Update</h2> <p>This fix has been merged into CI 2.2.1 (<a href="https://github.com/bcit-ci/CodeIgniter/commit/69b02d0f0bc46e914bed1604cfbd9bf74286b2e3" rel="noreferrer">https://github.com/bcit-ci/CodeIgniter/commit/69b02d0f0bc46e914bed1604cfbd9bf74286b2e3</a>). It's better to upgrade rather than modifying core framework files.</p>
8,763,046
Facebook page automatic "like" URL (for QR Code)
<p>I was wondering if one could construct a URL for automatically liking a Facebook page. Then this URL could be converted to a QR Code so people can automatically "like" your page by reading it with their smartphone. </p> <p>I have been searching a lot, but all I could find so far are commercial services like <a href="http://www.spotlike.com/" rel="noreferrer">Spotlike</a>, <a href="http://www.likify.net/" rel="noreferrer">Likify</a>, <a href="http://www.socialqrcode.com/" rel="noreferrer">Social QR Code</a> etc. I don't want a solution that relies on such commercial services. </p> <p>I am starting to suspect that Facebook has not enabled this possibility for understandable reasons (abuse and such). Still, I was hoping it would be possible to do this somehow, even by just creating my own intermediary service. In the latter case what would be basically required for creating such a service? </p> <hr> <p><strong>EDIT:</strong></p> <p>I already did try a URL like this: <a href="http://www.facebook.com/plugins/like.php?href=http://facebook.com/interlinkONE" rel="noreferrer">http://www.facebook.com/plugins/like.php?href=http://facebook.com/interlinkONE</a> </p> <p>This URL (also when encoded as a QR code) did not really give a desirable result on an iPhone, as it showed a blank page with a tiny "like" button that was barely discernible. Also, it did not appear to work even when I attempted to click the "like" button. </p> <p>Source: <a href="http://qreateandtrack.com/2010/10/18/how-to-create-qr-codes-for-the-facebook-like-button/" rel="noreferrer">http://qreateandtrack.com/2010/10/18/how-to-create-qr-codes-for-the-facebook-like-button/</a> </p>
8,765,572
6
0
null
2012-01-06 19:06:35.047 UTC
9
2013-10-04 09:14:40.577 UTC
2012-01-30 18:36:57.363 UTC
null
815,724
null
155,003
null
1
9
facebook|url|qr-code|smartphone
114,608
<p>I'm not an attorney, but clicking the like button without the express permission of a facebook user might be a violation of facebook policy. You should have your corporate attorney check out the facebook policy.</p> <p>You should encode the url to a page with a like button, so when scanned by the phone, it opens up a browser window to the like page, where now the user has the option to like it or not.</p>
8,567,058
FormStartPosition.CenterParent does not work
<p>In the following code, only the second method works for me (.NET 4.0). <code>FormStartPosition.CenterParent</code> does not center the child form over its parent. Why?</p> <p>Source: <a href="https://stackoverflow.com/questions/8566582/how-to-center-parent-a-non-modal-form-c/8566602#comment10620304_8566602">this SO question</a></p> <pre><code>using System; using System.Drawing; using System.Windows.Forms; class Program { private static Form f1; public static void Main() { f1 = new Form() { Width = 640, Height = 480 }; f1.MouseClick += f1_MouseClick; Application.Run(f1); } static void f1_MouseClick(object sender, MouseEventArgs e) { Form f2 = new Form() { Width = 400, Height = 300 }; switch (e.Button) { case MouseButtons.Left: { // 1st method f2.StartPosition = FormStartPosition.CenterParent; break; } case MouseButtons.Right: { // 2nd method f2.StartPosition = FormStartPosition.Manual; f2.Location = new Point( f1.Location.X + (f1.Width - f2.Width) / 2, f1.Location.Y + (f1.Height - f2.Height) / 2 ); break; } } f2.Show(f1); } } </code></pre>
8,567,083
14
0
null
2011-12-19 20:22:51.597 UTC
4
2021-11-29 23:09:30.127 UTC
2017-05-23 12:08:47.433 UTC
null
-1
null
600,135
null
1
38
c#|winforms|forms|parent-child|centering
33,005
<p>This is because you are not telling <code>f2</code> who its <code>Parent</code> is.</p> <p>If this is an MDI application, then <code>f2</code> should have its <code>MdiParent</code> set to <code>f1</code>.</p> <pre><code>Form f2 = new Form() { Width = 400, Height = 300 }; f2.StartPosition = FormStartPosition.CenterParent; f2.MdiParent = f1; f2.Show(); </code></pre> <p>If this is not an MDI application, then you need to call the <code>ShowDialog</code> method using <code>f1</code> as the parameter.</p> <pre><code>Form f2 = new Form() { Width = 400, Height = 300 }; f2.StartPosition = FormStartPosition.CenterParent; f2.ShowDialog(f1); </code></pre> <p>Note that <code>CenterParent</code> does not work correctly with <code>Show</code> since there is no way to set the <code>Parent</code>, so if <code>ShowDialog</code> is not appropriate, the manual approach is the only viable one.</p>
8,867,350
How to set a program's command line arguments for GHCi?
<p>Suppose some Haskell file is executed with</p> <pre><code>runghc Queens.hs gecode_compile </code></pre> <p>Now, this fails, and I want to debug it with <code>ghci</code>. How do I pass the option <code>gecode_compile</code> into the program, so <code>getArgs</code> will read it correctly?</p> <p>Thanks!!</p>
8,867,385
3
0
null
2012-01-15 03:33:23.22 UTC
11
2017-05-20 17:49:40.493 UTC
2017-05-20 17:49:40.493 UTC
null
1,663,462
null
81,636
null
1
44
haskell|ghci
10,298
<p>You can also set the command line arguments in ghci</p> <pre><code>ghci&gt; :set args foo bar ghci&gt; main </code></pre> <p>or</p> <pre><code>ghci&gt; :main foo bar </code></pre>
61,079,125
MatToolbar throws error when using it with Angular 9
<p>Angular version 9.2.0</p> <p>When I import the <code>MatToolbarModule</code> in a module and use it in the html template, then I get the following error message:</p> <blockquote> <p>This likely means that the library (@angular/material/toolbar) which declares MatToolbarModule has not been processed correctly by ngcc, or is not compatible with Angular Ivy. Check if a newer version of the library is available, and update if so. Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy.</p> <pre><code>8 export declare class MatToolbarModule { ~~~~~~~~~~~~~~~~ src/app/angular-material.module.ts:53:14 - error NG6002: Appears in the NgModule.imports of ComponentsModule, but itself has errors </code></pre> </blockquote> <p>Does anyone face the same issue?</p>
62,066,224
13
0
null
2020-04-07 11:34:24.773 UTC
4
2022-03-05 17:43:22.817 UTC
null
null
null
null
10,114,038
null
1
62
angular|angular-material
81,624
<p>Add below specific configuration in <code>package.json</code> and <code>npm install</code>.</p> <pre><code>{ &quot;scripts&quot;: { &quot;postinstall&quot;: &quot;ngcc&quot; } } </code></pre> <p><strong>Reference</strong>: <a href="https://angular.io/guide/ivy#speeding-up-ngcc-compilation" rel="noreferrer">https://angular.io/guide/ivy#speeding-up-ngcc-compilation</a></p>
48,290,976
Login with ASP Identity fails every time with "Not Allowed" (even when 'email' and 'username' have the same value))
<p>Registering a user works fine, as it logs in via this line:</p> <pre><code>await _signInManager.SignInAsync(user, isPersistent: model.RememberMe); </code></pre> <p>But if I want to log in with the same user again does not work (the Task Result always returned "Not Allowed").</p> <pre><code>var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: true); </code></pre> <p>I do realise that PasswordSignInAsync expects a USERNAME, not an EMAIL - but they are one and the same for my application.</p> <p>I have tried every variation of the log in methods, including checking if the user and passwords are correct (which all succeed), passing in the user object, altering the ViewModel property name, etc. </p> <p>Any ideas what needs to change?</p> <p>Similar issue for context: <a href="https://stackoverflow.com/questions/26430094/asp-net-identity-provider-signinmanager-keeps-returning-failure">ASP.NET Identity Provider SignInManager Keeps Returning Failure</a></p> <p>Thank you.</p>
48,292,037
3
0
null
2018-01-16 22:38:54.253 UTC
8
2020-06-23 10:07:44.167 UTC
null
null
null
null
1,819,747
null
1
30
c#|asp.net|asp.net-mvc|asp.net-core|.net-core
12,241
<p>Ok, I figured it out. I looked at the source code here - <a href="https://github.com/aspnet/Identity/blob/dev/src/Identity/SignInManager.cs" rel="noreferrer">https://github.com/aspnet/Identity/blob/dev/src/Identity/SignInManager.cs</a>.</p> <p>NotAllowed is only set here:</p> <pre><code> protected virtual async Task&lt;SignInResult&gt; PreSignInCheck(TUser user) { if (!await CanSignInAsync(user)) { return SignInResult.NotAllowed; } if (await IsLockedOut(user)) { return await LockedOut(user); } return null; } </code></pre> <p>So I drilled down into CanSignInAsync...</p> <pre><code>public virtual async Task&lt;bool&gt; CanSignInAsync(TUser user) { if (Options.SignIn.RequireConfirmedEmail &amp;&amp; !(await UserManager.IsEmailConfirmedAsync(user))) { Logger.LogWarning(0, "User {userId} cannot sign in without a confirmed email.", await UserManager.GetUserIdAsync(user)); return false; } if (Options.SignIn.RequireConfirmedPhoneNumber &amp;&amp; !(await UserManager.IsPhoneNumberConfirmedAsync(user))) { Logger.LogWarning(1, "User {userId} cannot sign in without a confirmed phone number.", await UserManager.GetUserIdAsync(user)); return false; } return true; } </code></pre> <p>Oh, I know where this is going. Let's take a look at my Startup.cs Configuration.</p> <pre><code>services.Configure&lt;IdentityOptions&gt;(options =&gt; { ... options.SignIn.RequireConfirmedEmail = true; ... } </code></pre> <p>Oh dear, OK.</p> <p>All I had to do was pop into the database and set my user as EmailConfirmed = true. PEBCAK.</p> <p>"Not Allowed" makes sense, but there was no error message that came back with it - so it wasn't the best way to know what's going on. Luckily .NET Core is easy to dive into the source code with.</p> <p>Hope this helps someone.</p>
47,580,247
Optional environment variables in Spring app
<p>In my Spring Boot app's <code>application.properties</code> I have this definition:</p> <pre><code>someProp=${SOME_ENV_VARIABLE} </code></pre> <p>But this is an optional value only set in certain environments, I use it like this</p> <pre><code>@Value("${someProp:#{null}}") private String someProp; </code></pre> <p>Surprisingly I get this error when the env. var doesn't exist<br> <code>Could not resolve placeholder 'SOME_ENV_VARIABLE' in string value "${SOME_ENV_VARIABLE}"</code><br> I was expecting Spring to just set a blank value if not found in any <code>PropertySource</code>. </p> <p>How to make it optional?</p>
47,581,132
3
2
null
2017-11-30 18:26:21.477 UTC
7
2021-12-24 11:41:49.467 UTC
null
null
null
null
961,721
null
1
41
spring|spring-boot|environment-variables
35,144
<p>Provide a default value in the <code>application.properties</code></p> <pre><code>someProp=${SOME_ENV_VARIABLE:#{null}} </code></pre> <p>When used like <code>@Value("${someProp})</code>, this will correctly evaluate to <code>null</code>. First, if <code>SOME_ENV_VARIABLE</code> is not found when <code>application.properties</code> is being processed, its value becomes the string literal "#{null}". Then, <code>@Value</code> evaluates <code>someProp</code> as a SpEL expression, which results in <code>null</code>. The actual value can be verified by looking at the property in the <code>Environment</code> bean.</p> <p>This solution utilizes the default value syntax specified by the <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/config/PlaceholderConfigurerSupport.html" rel="noreferrer"><code>PlaceholderConfigurerSupport</code></a> class</p> <blockquote> <p>Default property values can be defined globally for each configurer instance via the properties property, or on a property-by-property basis using the default value separator which is ":" by default and customizable via setValueSeparator(String).</p> </blockquote> <p>and <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#expressions-templating" rel="noreferrer">Spring SpEL expression templating</a>. </p> <p>From Spring Boot docs on <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html" rel="noreferrer">externalized configuration</a></p> <blockquote> <p>Finally, while you can write a SpEL expression in @Value, such expressions are not processed from Application property files.</p> </blockquote>
43,555,378
ts An async function or method in ES5/ES3 requires the 'Promise' constructor
<p>Hello I'm Using async/await in my TypeScript Project, But I Get this log:</p> <p><em>[ts] An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your <code>--lib</code> option.</em></p> <p>How Can I Solve That?</p>
43,555,510
13
0
null
2017-04-22 04:53:31.813 UTC
13
2022-06-01 11:11:56.603 UTC
null
null
null
null
7,428,622
null
1
137
typescript|async-await
99,003
<p>As the error message says, add <code>lib: es2015</code> to your tsconfig.json</p> <pre><code>// tsconfig.json { "compilerOptions": { "lib": [ "es2015" ] } } </code></pre> <p>UPDATE: if this doesn't work for you, try this:</p> <p>JetBrains IDE such as WebStorm, use its own implementation by default. Make sure you configure it to use TypeScript language service instead.</p> <p>For Visual Studio, the project files and <code>tsconfig.json</code> are mutually exclusive. You will need to configure your project directly.</p> <p><a href="https://github.com/Microsoft/TypeScript/issues/3983#issuecomment-123861491" rel="noreferrer">https://github.com/Microsoft/TypeScript/issues/3983#issuecomment-123861491</a></p>
22,358,831
iOS 7.1 UitableviewCell content overlaps with ones below
<p>So I have code, which is sucessfully working on iOS 7.0 but not in 7.1. I have a simple tableview, with code:</p> <pre><code>- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 10; } -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 70.0; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; for (UIView *view in cell.contentView.subviews) { [view removeFromSuperview]; } UILabel *label = [[UILabel alloc] init]; label.text = [NSString string]; for (NSInteger i = 0; i &lt; 20; i++) { label.text = [label.text stringByAppendingString:@"label String "]; } label.translatesAutoresizingMaskIntoConstraints = NO; label.numberOfLines = 0; label.lineBreakMode = NSLineBreakByWorldWrapping; //label.lineBreakMode = NSLineBreakByTruncatingTail; //I have tried this too [cell.contentView addSubview:label]; NSDictionary *dict = NSDictionaryOfVariableBindings(label); [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-8-[label]-8-|" options:0 metrics:nil views:dict]]; [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-8-[label]" options:0 metrics:nil views:dict]]; if (indexPath.row == 0) { label.textColor = [UIColor colorWithRed:1.0 green:0 blue:0 alpha:1.0]; } else if (indexPath.row == 1) { label.textColor = [UIColor colorWithRed:0 green:1.0 blue:0 alpha:1.0]; } else if (indexPath.row == 2) { label.textColor = [UIColor colorWithRed:0 green:0 blue:1.0 alpha:1.0]; } else { label.textColor = [UIColor colorWithWhite:0.3 alpha:1.0]; } cell.backgroundColor = [UIColor colorWithWhite:1.0 alpha:1.0]; return cell; } </code></pre> <p>I have 1section with 10rows. With each row reused I delete all subviews from contentView(I tried alloc-init UITableViewCell, but came with the same results). </p> <p>On iOS 7.0, UILabel is displayed only in cell it belongs to. But in 7.1 UILabel continues displaying over another cells. What is interresting, that when I click on cell, it stop being overlaping by anothers, but only till I click on cell above. My question is, how to make it work on 7.1devices like on 7.0ones. </p> <p>I tried both simulator and device and I took a look at iOS 7.1 API Diffs, but found nothing related to this. </p> <p>Maybe it is issue of Auto Layout, that i have variable height of UILabel, but I need to do so. I want to have all text in UILabel, but display only part of UILabel, that can be displayed in a cell, which is default behavior in 7.0, but 7.1 changes this and I don't why why and how to deal with it.</p> <p>This is dropbox folder for images with detail explanation: <a href="https://www.dropbox.com/sh/cj11uzcz3j65vil/wmr74b9W0F">Folder with images</a></p> <p>Update: I tried things like tese, but nothing worked for me.</p> <pre><code>cell.frame = CGRectMake(0, 0, self.tableView.frame.size.width, 70); cell.contentView.frame = CGRectMake(0, 0, self.tableView.frame.size.width, 70); cell.opaque = NO; cell.contentView.opaque = NO; cell.clearsContextBeforeDrawing = NO; cell.contentView.clearsContextBeforeDrawing = NO; cell.clipsToBounds = NO; cell.contentView.clipsToBounds = NO; </code></pre>
22,359,028
7
0
null
2014-03-12 17:07:05.357 UTC
12
2019-11-10 15:23:03.647 UTC
2014-05-16 15:19:50.383 UTC
null
2,424,762
null
3,396,994
null
1
31
ios|uitableview|uilabel|autolayout|ios7.1
30,824
<p>The issue has to do with the height of your cell. It isn't going to dynamically adjust that for you.</p> <p>You'll probably notice that as you scroll and the view above goes out of view the overlapping text will disappear with it.</p> <p>If you are wanting your text to clip at a certain height, then you need to set the number of lines, rather than setting it to 0 since that will let it continue forever.</p> <p>The <code>lineBreakMode</code> won't take effect since it isn't stopped.</p> <p>Optionally you could try to set clipping on the contentView to make sure all subviews stay inside.</p> <p>Depending on the end result you want, you could do dynamic heights and change based on the content. There are a bunch of SO questions related to doing this.</p> <h2>Update - clipping the contentView</h2> <p>I'd have to try it out myself, but in lieu of that, here are a couple links related to clipping the contentView:</p> <ul> <li><a href="https://stackoverflow.com/questions/18877895/how-to-stop-uitableview-from-clipping-uitableviewcell-contents-in-ios-7">stop the clipping of contentView</a> - you'd actually want to do the opposite.</li> <li><a href="https://stackoverflow.com/questions/2842964/adding-a-subview-larger-than-cellheight-to-a-uitableviewcell">adding subview</a> - looks similar to what you are trying to do.</li> </ul> <p>Looks like this works:</p> <pre><code>cell.clipsToBounds = YES; </code></pre>
41,679,324
How do I pass parent state to its child components?
<p>I am new in React ES6 and I think I am modifying the state in a wrong way. My code is like this when I set state on parent component:</p> <pre><code>class App extends React.Component { constuctor(props) { super(props); this.state = {name:"helloworld"}; } render() { return( &lt;ChildComponent parentObj={this} /&gt; // parentObj for parent context as props on child components ); } } </code></pre> <p>My problem is in other child components, I have to do it repeatitively, is there another way of doing it? I have no problem with React.createClass, but I want to code in es6 so i have this problem. </p>
41,679,634
2
1
null
2017-01-16 15:04:52.877 UTC
8
2020-06-12 13:34:06.433 UTC
2020-06-12 13:34:06.433 UTC
null
1,264,804
null
5,288,560
null
1
21
reactjs|ecmascript-6
39,418
<p>If you wanna pass the state {name:"helloworld"} do it like that:</p> <pre><code>class App extends React.Component { constuctor(props) { super(props); this.state = {name:"helloworld"}; } render() { return( &lt;ChildComponent {...this.state} /&gt; ); } } </code></pre> <p>and in the child component you can do:</p> <pre><code>&lt;Text&gt;{this.props.name}&lt;/Text&gt; </code></pre> <p>But If you want to pass the props of the component to it's child:</p> <pre><code> class App extends React.Component { constuctor(props) { super(props); this.state = {name:"helloworld"}; } render() { return( &lt;ChildComponent {...this.props} /&gt; ); } } </code></pre> <p>and in the child component you can do:</p> <pre><code>&lt;Text&gt;{this.props.stuff}&lt;/Text&gt;//place stuff by any property name in props </code></pre> <p>Now if you want to update the state of parent component from the child component you will need to pass a function to the child component:</p> <pre><code> class App extends React.Component { constuctor(props) { super(props); this.state = {name:"helloworld"}; } update(name){ this.setState({name:name})// or with es6 this.setState({name}) } render() { return( &lt;ChildComponent {...this.props, update: this.update.bind(this)} /&gt; ); } } </code></pre> <p>and then in child component you can use this : <code>this.props.update('new name')</code></p> <p><strong>UPDATE</strong> </p> <p><strong><em>use more es6 and removed constructor</em></strong></p> <pre><code>class App extends React.Component { state = {name:"helloworld"}; // es6 function, will be bind with adding .bind(this) update = name =&gt; { this.setState({name:name})// or with es6 this.setState({name}) } render() { // notice that we removed .bind(this) from the update return( //send multiple methods using ',' &lt;ChildComponent {...this.props, update = this.update} /&gt; ); } } </code></pre>
42,017,587
how to use php explode in laravel?
<pre><code> $user = $this-&gt;user; $user-&gt;name = $request['name']; $user-&gt;email = $request['email']; $user-&gt;password = $request['password']; $user-&gt;save(); $name = explode(' ' ,$user-&gt;name); $profile= $user-&gt;userdetail()-&gt;create([ 'user_id' =&gt; $request-&gt;input('id'), 'first_name' =&gt; &lt;the value of the first exploded string&gt; 'last_name' =&gt; the value of the secondexploded string ]); return redirect('confirmation'); } </code></pre> <p>how to split two words using explode function in php? For example i registered wth name of JOhn doe I want to create in my userdetail table the first_name of john and last_name of doe. How can i do it/</p>
42,017,605
3
2
null
2017-02-03 05:48:23.167 UTC
5
2018-08-29 05:03:15.54 UTC
null
null
null
null
6,813,433
null
1
10
laravel
43,965
<p><a href="http://php.net/manual/en/function.explode.php" rel="noreferrer"><code>explode()</code></a> returns an array of strings, so you can access elements by using keys:</p> <pre><code>$profile = $user-&gt;userdetail()-&gt;create([ 'user_id' =&gt; $request-&gt;input('id'), 'first_name' =&gt; $name[0], 'last_name' =&gt; $name[1] ]); </code></pre>
36,562,549
What to do when autofilter in VBA returns no data?
<p>I am trying to filter a range of values and based on my criteria, at times I might have no data that fits my criteria. In that case, I do not want to copy any data from the filtered data. If there is filtered data, then I would like to copy it.</p> <p>Here is my code:</p> <pre><code>With Workbooks(KGRReport).Worksheets(spreadSheetName).Range("A1:I" &amp; lastrowinSpreadSheet) .AutoFilter Field:=3, Criteria1:=LimitCriteria, Operator:=xlFilterValues 'Do the filtering for Limit .AutoFilter Field:=9, Criteria1:=UtilizationCriteria, Operator:=xlFilterValues 'Do the filtering for Bank/NonBank End With 'Clear the template Workbooks(mainwb).Worksheets("Template").Activate Workbooks(mainwb).Worksheets("Template").Rows(7 &amp; ":" &amp; Rows.Count).Delete 'Copy the filtered data Workbooks(KGRReport).Activate Set myRange = Workbooks(KGRReport).Worksheets(spreadSheetName).Range("B2:H" &amp; lastrowinSpreadSheet).SpecialCells(xlVisible) For Each myArea In myRange.Areas For Each rw In myArea.Rows strFltrdRng = strFltrdRng &amp; rw.Address &amp; "," Next Next strFltrdRng = Left(strFltrdRng, Len(strFltrdRng) - 1) Set myFltrdRange = Range(strFltrdRng) myFltrdRange.Copy strFltrdRng = "" </code></pre> <p>It is giving me an error at </p> <pre><code>Set myRange = Workbooks(KGRReport).Worksheets(spreadSheetName).Range("B2:H" &amp; lastrowinSpreadSheet).SpecialCells(xlVisible) </code></pre> <p>When there is no data at all, it is returning an error: "No cells found".</p> <p>Tried error handling like this post: <a href="https://stackoverflow.com/questions/25380886/1004-error-no-cells-were-found-easy-solution">1004 Error: No cells were found, easy solution?</a></p> <p>But it was not helping. Need some guidance on how to solve this.</p>
36,563,207
5
2
null
2016-04-12 02:23:22.383 UTC
1
2018-08-10 11:51:57.18 UTC
2017-05-23 12:15:51.85 UTC
null
-1
null
1,152,000
null
1
6
excel|vba|autofilter
44,069
<p>Try error handling like so:</p> <pre><code>Dim myRange As Range On Error Resume Next Set myRange = Range("your range here").SpecialCells(xlVisible) On Error GoTo 0 If myRange Is Nothing Then MsgBox "no cells" Else 'do stuff End If </code></pre>
34,956,899
Does Spring @RequestBody support the GET method?
<p>I am trying to carry JSON data in an HTTP GET request message, but my Spring MVC server can't seem to retrieve the JSON data from the GET request body.</p>
34,956,992
2
1
null
2016-01-22 22:20:59.163 UTC
3
2021-08-08 00:46:46.133 UTC
2016-01-22 23:26:53.263 UTC
null
5,759,943
null
5,828,414
null
1
29
spring-mvc|get
39,622
<p>HTTP's <code>GET</code> method does not include a request body as part of the spec. Spring MVC respects the HTTP specs. Specifically, servers are allowed to discard the body. The request URI should contain everything needed to formulate the response.</p> <p>If you need a request body, change the request type to POST, which does include the request body.</p>
24,005,678
What is the equivalent of an Objective-C id in Swift?
<p>I'm trying to use an @IBAction to tie up a button click event to a Swift method. In Objective-C the parameter type of the IBAction is id. What is the equivalent of id in Swift?</p>
24,005,679
2
0
null
2014-06-03 01:14:43.513 UTC
9
2019-01-03 08:07:48.54 UTC
2019-01-03 08:07:48.54 UTC
null
100,297
null
196,964
null
1
62
objective-c|swift
23,421
<h1>Swift 3</h1> <p><code>Any</code>, if you know the sender is never <code>nil</code>.</p> <pre><code>@IBAction func buttonClicked(sender : Any) { println("Button was clicked", sender) } </code></pre> <p><code>Any?</code>, if the sender could be <code>nil</code>.</p> <pre><code>@IBAction func buttonClicked(sender : Any?) { println("Button was clicked", sender) } </code></pre> <h1>Swift 2</h1> <p><code>AnyObject</code>, if you know the sender is never <code>nil</code>.</p> <pre><code>@IBAction func buttonClicked(sender : AnyObject) { println("Button was clicked", sender) } </code></pre> <p><code>AnyObject?</code>, if the sender could be <code>nil</code>.</p> <pre><code>@IBAction func buttonClicked(sender : AnyObject?) { println("Button was clicked", sender) } </code></pre>
24,137,212
"initialize" class method for classes in Swift?
<p>I'm looking for behavior similar to Objective-C's <code>+(void)initialize</code> class method, in that the method is called once when the class is initialized, and never again thereafter.</p> <p>A simple <code>class init () {}</code> in a <code>class</code> closure would be really sleek! And obviously when we get to use "<code>class var</code>s" instead of "<code>static var</code>s in a struct closure", this will all match really well!</p>
24,137,213
6
0
null
2014-06-10 09:16:42.513 UTC
19
2019-05-29 10:57:33.153 UTC
null
null
null
null
2,228,559
null
1
77
ios|swift
66,785
<p>If you have an Objective-C class, it's easiest to just override <code>+initialize</code>. However, make sure <strong>subclasses</strong> of your class also override <code>+initialize</code> or else your class's <code>+initialize</code> may get called more than once! If you want, you can use <code>dispatch_once()</code> (mentioned below) to safeguard against multiple calls.</p> <pre><code>class MyView : UIView { override class func initialize () { // Do stuff } } </code></pre> <p>&nbsp;</p> <p>If you have a Swift class, the best you can get is <code>dispatch_once()</code> inside the <code>init()</code> statement.</p> <pre><code>private var once = dispatch_once_t() class MyObject { init () { dispatch_once(&amp;once) { // Do stuff } } } </code></pre> <p>This solution differs from <code>+initialize</code> (which is called the first time an Objective-C class is messaged) and thus isn't a true answer to the question. But it works good enough, IMO.</p>
35,974,249
Using WireMock with SOAP Web Services in Java
<p>I am totally new to <a href="http://wiremock.org/index.html" rel="noreferrer">WireMock</a>.</p> <p>Until now, I have been using mock responses using SOAPUI. My use case is simple:</p> <p>Just firing SOAP XML requests to different endpoints (<a href="http://localhost:9001/endpoint1" rel="noreferrer">http://localhost:9001/endpoint1</a>) and getting canned XML response back. But MockWrire has to be deployed as a standalone service onto a dedicated server which will act a central location from where mock responses will be served.</p> <p>Just wanted some starting suggestions. As I can see WireMock is more suitable towards REST web services. So my doubts are:</p> <p>1) Do I need to deploy it to a java web server or container to act as always running standalone service. I read that you can just spin off by using</p> <pre><code>java -jar mockwire.jar --port [port_number] </code></pre> <p>2) Do I need to use MockWire APIs? Do I need to make classes for my use case? In my case, requests will be triggered via JUnit test cases for mocking.</p> <p>3) How do I achieve simple URL pattern matching? As stated above, I just need simple mocking i.e get response when request is made to <a href="http://localhost:9001/endpoint1" rel="noreferrer">http://localhost:9001/endpoint1</a></p> <p>4) Is there a better/easier framework for my usecase? I read about Mockable but it has restrictions for 3 team members and demo domain in free tier.</p>
35,975,602
3
1
null
2016-03-13 18:46:12.24 UTC
9
2022-05-02 20:51:31.057 UTC
null
null
null
null
673,910
null
1
14
java|web-services|soap|mocking|wiremock
48,083
<p>I'm WireMock's creator.</p> <p>I've used WireMock to mock a collection of SOAP interfaces on a client project quite recently, so I can attest that it's possible. As for whether it's better or worse than SOAP UI, I'd say there are some definite upsides, but with some tradeoffs. A major benefit is the relative ease of deployment and programmatic access/configuration, and support for things like HTTPS and low-level fault injection. However, you need to do a bit more work to parse and generate SOAP payloads - it won't do code/stub generation from WSDL like SOAP UI will.</p> <p>My experience is that tools like SOAP UI will get you started faster, but tend to result in higher maintenance costs in the long run when your test suite grows beyond trivial.</p> <p>To address your points in turn: 1) If you want your mocks to run on a server somewhere, the easiest way to do this is to run the standalone JAR as you've described. I'd advise against trying to deploy it to a container - this option really only exists for when there's no alternative.</p> <p>However, if you just want to run integration tests or totally self-contained functional tests, I'd suggest using the JUnit rule. I'd say it's only a good idea to run it in a dedicated process if either a) you're plugging other deployed systems into it, or b) you're using it from a non-JVM language.</p> <p>2) You'd need to configure it in one of 3 ways 1) the Java API, 2) JSON over HTTP, or 3) JSON files. 3) is probably closest to what you're used to with SOAP UI.</p> <p>3) See <a href="http://wiremock.org/stubbing.html" rel="noreferrer">http://wiremock.org/stubbing.html</a> for lots of stubbing examples using both JSON and Java. Since SOAP tends to bind to fixed endpoint URLs, you probably want <code>urlEqualTo(...)</code>. When I've stubbed SOAP in the past I've tended to XML match on the entire request body (see <a href="http://wiremock.org/stubbing.html#xml-body-matching" rel="noreferrer">http://wiremock.org/stubbing.html#xml-body-matching</a>). I'd suggest investing in writing a few Java builders to emit the request and response body XML you need.</p> <p>4) <a href="http://mock-server.com/" rel="noreferrer">Mock Server</a> and <a href="http://betamax.software/" rel="noreferrer">Betamax</a> are both mature alternatives to WireMock, but AFAIK they don't offer any more explicit SOAP support.</p>
41,511,034
How to rename AWS S3 Bucket
<p>After all the tough work of migration etc, I just realised that I need to serve the content using CNAME (e.g media.abc.com). The bucket name needs to start with media.abc.com/S3/amazon.com to ensure it works perfectly.</p> <p>I just realised that S3 doesn't allow direct rename from the console.</p> <p>Is there any way to work around this?</p>
41,515,547
3
0
null
2017-01-06 17:30:54.61 UTC
41
2022-05-31 19:12:04.397 UTC
2022-02-16 06:33:35.307 UTC
null
992,887
null
1,026,780
null
1
207
amazon-web-services|amazon-s3|cname
126,686
<p>I think only way is to create a new bucket with correct name and then copy all your objects from old bucket to new bucket. You can do it using Aws CLI.</p>
6,159,186
How do I write text over a picture in Android and save it?
<p>How can I write text on an image and then save it in Android?</p> <p>Basically I want to let user write something on the images which my camera app will click for them. I can write and show it to them using the onDraw method on the preview of the camera. But after the user has clicked the picture I want to write the text over the picture and then save it.</p>
6,159,192
4
0
null
2011-05-28 01:51:31.057 UTC
18
2016-09-19 13:52:23.12 UTC
2011-11-21 18:38:35.397 UTC
null
300,977
null
418,366
null
1
26
android
39,363
<p>You have to implement a canvas that allows the user to draw on it and then set the background of that canvas to that particular image. This is just a guess but its somewhere there abouts.</p>
6,104,774
How many table partitions is too many in Postgres?
<p>I'm partitioning a very large table that contains temporal data, and considering to what granularity I should make the partitions. The Postgres <a href="http://www.postgresql.org/docs/8.3/interactive/ddl-partitioning.html" rel="noreferrer">partition documentation</a> claims that "large numbers of partitions are likely to increase query planning time considerably" and recommends that partitioning be used with "up to perhaps a hundred" partitions.</p> <p>Assuming my table holds ten years of data, if I partitioned by week I would end up with over 500 partitions. Before I rule this out, I'd like to better understand what impact partition quantity has on query planning time. Has anyone benchmarked this, or does anyone have an understanding of how this works internally?</p>
6,131,446
4
1
null
2011-05-24 01:10:22.313 UTC
6
2011-05-25 21:54:03.117 UTC
null
null
null
null
51,025
null
1
30
performance|postgresql|partitioning
18,067
<p>The query planner has to do a linear search of the constraint information for every partition of tables used in the query, to figure out which are actually involved--the ones that can have rows needed for the data requested. The number of query plans the planner considers grows exponentially as you join more tables. So the exact spot where that linear search adds up to enough time to be troubling really depends on query complexity. The more joins, the worse you will get hit by this. The "up to a hundred" figure came from noting that query planning time was adding up to a non-trivial amount of time even on simpler queries around that point. On web applications in particular, where latency of response time is important, that's a problem; thus the warning.</p> <p>Can you support 500? Sure. But you are going to be searching every one of 500 check constraints for every query plan involving that table considered by the optimizer. If query planning time isn't a concern for you, then maybe you don't care. But most sites end up disliking the proportion of time spent on query planning with that many partitions, which is one reason why monthly partitioning is the standard for most data sets. You can easily store 10 years of data, partitioned monthly, before you start crossing over into where planning overhead starts to be noticeable. </p>
52,535,985
Couldn't connect to server 127.0.0.1:27017 connection attempt failed MongoDB
<p>I am working on Ubuntu OS 16.04. I am starting mongodb using commands:: <code>sudo service mongod start</code> and then <code>mongo</code> </p> <p>It generated this error for me::</p> <pre><code>MongoDB shell version v4.0.1 connecting to: mongodb://127.0.0.1:27017 2018-09-27T16:50:41.345+0530 E QUERY [js] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused : connect@src/mongo/shell/mongo.js:257:13 @(connect):1:6 exception: connect failed </code></pre> <p>Now I am not able to start mongodb. How to resolve this error and what are the causes of these error. I tried all of solution for this problem but didn't find any solution.</p>
52,536,473
9
2
null
2018-09-27 11:30:47.033 UTC
8
2021-04-08 02:54:19.463 UTC
2019-06-29 05:38:22.863 UTC
null
6,487,762
null
6,487,762
null
1
15
mongodb
45,526
<p>mongod --repair worked for me ,</p> <pre><code>sudo mongod --repair sudo mongod </code></pre> <p>Then open a different tab/terminal:</p> <pre><code>mongo </code></pre> <p>After this your local setup will work properly</p>
34,612,790
How to assign rawValue of enum to variable with ObjectMapper?
<p>Hello I am using <a href="https://github.com/Hearst-DD/ObjectMapper">Object Mapper</a> with Alamofire in Swift and I am trying to map enum raw value to real Enum. </p> <p>Here is my enum and also the code I am trying to use in function <em>mapping</em>. Can you please help me what to pass as argument to EnumTransform or how to modify the code? I know I can read the value as string and the use LevelType(rawValue: stringValue). </p> <p>Thanks in advance.</p> <pre><code>enum LevelType : String { case NEW = "NEW" case UPDATE = "UPDATE" } func mapping(map: Map) { typeEnum &lt;- (map[“type”], EnumTransformable(???) ) } </code></pre>
34,614,880
2
1
null
2016-01-05 13:23:32.207 UTC
7
2018-10-17 15:37:02.977 UTC
2016-01-05 14:28:07.62 UTC
null
2,303,865
null
1,692,555
null
1
31
swift|alamofire|objectmapper
10,400
<p>You don't have to pass an argument at all. All you have to do is to specify enum type as generic argument and ObjectMapper will take care for all enum initialization procedures.</p> <pre><code> typeEnum &lt;- (map["type"],EnumTransform&lt;LevelType&gt;()) </code></pre>
5,611,448
Tab to select autocomplete item in eclipse?
<p>I can't find either the term <strong>autocomplete</strong> or <strong>intellisense</strong> in Preferences->General->Keys in Eclipse 3.6.2.</p> <p>I don't want to press enter to select an autocomplete item when I write code. Can I configure Eclipse to accept an autocomplete item with the <em>tab button</em>?</p>
55,544,094
5
9
null
2011-04-10 11:28:42.617 UTC
5
2019-04-05 22:24:45.89 UTC
2011-04-11 09:15:40.047 UTC
null
480,986
null
480,986
null
1
36
eclipse|configuration|autocomplete|intellisense|preferences
33,466
<p>Just got it, go to Window>Preferences>General->Keys and look for "Word completion" as said before. Then near the bottom is "Binding" and to the right of it, a box with an arrow, clicking there you can select "Tab" to use Tabulator for autocomplete.</p>
6,096,492
Node.js and Express session handling - Back button problem
<p>I have a restricted area '/dashboard' in my Express application. I use a very small function to limit the access: </p> <pre><code>app.get('/dashboard', loadUser, function(req, res){ res.render('dashboard', { username: req.session.username }); }); function loadUser(req, res, next){ if (req.session.auth) { next(); } else { res.redirect('/login'); } }; </code></pre> <p>The problem is that when I logout a user by calling...</p> <pre><code>app.get('/logout', function(req, res){ if (req.session) { req.session.auth = null; res.clearCookie('auth'); req.session.destroy(function() {}); } res.redirect('/login'); }); </code></pre> <p>... the session is killed but <strong>when I hit Back Button in my browser I got the restricted page from browser's cache. This means no GET on '/dashboard' and no user login validation.</strong></p> <p>I tried using no-cache in meta (Jade Template) but it still doesn't work.</p> <pre><code>meta(http-equiv='Cache-Control', content='no-store, no-cache, must-revalidate') meta(http-equiv='Pragma', content='no-cache') meta(http-equiv='Expires', content='-1') </code></pre> <p>Anyone?</p>
6,505,456
6
0
null
2011-05-23 11:23:08.357 UTC
14
2022-05-30 14:46:48.43 UTC
null
null
null
null
591,939
null
1
19
session|node.js|express
23,934
<p>Josh's answer sadly didn't work for me. But after some searching I found this question: <a href="https://stackoverflow.com/questions/23094/whats-the-best-way-to-deal-with-cache-and-the-browser-back-button">What&#39;s the best way to deal with cache and the browser back button?</a></p> <p>and adopted the answer there to this node.js/express problem. You just have to change the following line</p> <pre><code>res.header('Cache-Control', 'no-cache'); </code></pre> <p>to</p> <pre><code>res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0'); </code></pre> <p>Now, everytime I use the browser back button, the page is reloaded and not cached.</p> <p><strong>* update for express v4.x *</strong></p> <pre><code>// caching disabled for every route server.use(function(req, res, next) { res.set('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0'); next(); }); // otherwise put the res.set() call into the route-handler you want </code></pre>
5,990,240
redirect all .html extensions to .php
<p>I want to update all the pages on a website to use include for the footer and header. So I have to change a lot of .html pages to .php.</p> <p>So i'm looking for a way to redirect all pages that end with .html to the same url but ending in .php.</p>
5,990,276
6
0
null
2011-05-13 09:59:38.783 UTC
6
2019-05-04 14:11:52.707 UTC
null
null
null
null
196,361
null
1
23
.htaccess
50,066
<pre><code>RewriteEngine On RewriteRule ^(.*)\.html$ $1.php [L] </code></pre> <p>If you want it to be done as a redirect instead of just a rewrite modify the <code>[L]</code> to <code>[L,R]</code></p>
5,876,332
How can I differentiate an object literal from other Javascript objects?
<p><strong>Update</strong>: I'm rephrasing this question, because the important point to me is identifying the object literal:</p> <p>How can I tell the difference between an object literal and any other Javascript object (e.g. a DOM node, a Date object, etc.)? How can I write this function:</p> <pre><code>function f(x) { if (typeof x === 'object literal') console.log('Object literal!'); else console.log('Something else!'); } </code></pre> <p>So that it only prints <code>Object literal!</code> as a result of the first call below:</p> <pre><code>f({name: 'Tom'}); f(function() {}); f(new String('howdy')); f('hello'); f(document); </code></pre> <hr> <p><strong>Original Question</strong></p> <p>I'm writing a Javascript function that is designed to accept an object literal, a string, or a DOM node as its argument. It needs to handle each argument slightly differently, but at the moment I can't figure out how to differentiate between a DOM node and a plain old object literal.</p> <p>Here is a greatly simplified version of my function, along with a test for each kind of argument I need to handle:</p> <pre><code>function f(x) { if (typeof x == 'string') console.log('Got a string!'); else if (typeof x == 'object') console.log('Got an object literal!'); else console.log('Got a DOM node!'); } f('hello'); f({name: 'Tom'}); f(document); </code></pre> <p>This code will log the same message for the second two calls. I can't figure out what to include in the <code>else if</code> clause. I've tried other variations like <code>x instanceof Object</code> that have the same effect.</p> <p>I understand that this might be bad API/code design on my part. Even if it is, I'd still like to know how to do this.</p>
5,878,101
6
4
null
2011-05-03 22:11:39.387 UTC
8
2022-05-02 23:32:31.5 UTC
2022-05-02 23:32:31.5 UTC
null
8,910,547
null
151,221
null
1
35
javascript|types|comparison|object-literal
21,894
<blockquote> <p>How can I tell the difference between an object literal and any other Javascript object (e.g. a DOM node, a Date object, etc.)?</p> </blockquote> <p>The short answer is you can't.</p> <p>An <em>object literal</em> is something like:</p> <pre><code>var objLiteral = {foo: 'foo', bar: 'bar'}; </code></pre> <p>whereas the same object created using the <em>Object constructor</em> might be:</p> <pre><code>var obj = new Object(); obj.foo = 'foo'; obj.bar = 'bar'; </code></pre> <p>I don't think there is any reliable way to tell the difference between how the two objects were created.</p> <p>Why is it important?</p> <p>A general feature testing strategy is to test the properties of the objects passed to a function to determine if they support the methods that are to be called. That way you don't really care how an object is created.</p> <p>You can employ "duck typing", but only to a limited extent. You can't guarantee that just because an object has, for example, a <code>getFullYear()</code> method that it is a Date object. Similarly, just because it has a <em>nodeType</em> property doesn't mean it's a DOM object.</p> <p>For example, the jQuery <code>isPlainObject</code> function thinks that if an object has a nodeType property, it's a DOM node, and if it has a <code>setInterval</code> property it's a Window object. That sort of duck typing is extremely simplistic and will fail in some cases.</p> <p>You may also note that jQuery depends on properties being returned in a specific order - another dangerous assumption that is not supported by any standard (though some supporters are trying to change the standard to suit their assumed behaviour).</p> <p>Edit 22-Apr-2014: in version 1.10 jQuery includes a <em>support.ownLast</em> property based on testing a single property (apparently this is for IE9 support) to see if inherited properties are enumerated first or last. This continues to ignore the fact that an object's properties can be returned in <strong>any</strong> order, regardless of whether they are inherited or own, and may be jumbled.</p> <p>Probably the simplest test for "plain" objects is:</p> <pre><code>function isPlainObj(o) { return typeof o == 'object' &amp;&amp; o.constructor == Object; } </code></pre> <p>Which will always be true for objects created using object literals or the Object constructor, but may well give spurious results for objects created other ways and may (probably will) fail across frames. You could add an <code>instanceof</code> test too, but I can't see that it does anything that the constructor test doesn't.</p> <p>If you are passing ActiveX objects, best to wrap it in try..catch as they can return all sorts of weird results, even throw errors.</p> <p><strong><em>Edit 13-Oct-2015</em></strong></p> <p>Of course there are some traps:</p> <pre><code>isPlainObject( {constructor: 'foo'} ); // false, should be true // In global scope var constructor = Object; isPlainObject( this ); // true, should be false </code></pre> <p>Messing with the constructor property will cause issues. There are other traps too, such as objects created by constructors other than Object.</p> <p>Since ES5 is now pretty much ubiquitous, there is <a href="http://ecma-international.org/ecma-262/5.1/#sec-15.2.3.2" rel="noreferrer"><em>Object.getPrototypeOf</em></a> to check the <code>[[Prototype]]</code> of an object. If it's the buit–in <em>Object.prototype</em>, then the object is a plain object. However, some developers wish to create truly "empty" objects that have no inherited properties. This can be done using:</p> <pre><code>var emptyObj = Object.create(null); </code></pre> <p>In this case, the <code>[[Prototype]]</code> property is <em>null</em>. So simply checking if the internal prototype is <em>Object.prototype</em> isn't sufficient.</p> <p>There is also the reasonably widely used:</p> <pre><code>Object.prototype.toString.call(valueToTest) </code></pre> <p>that was specified as returning a string based on the internal <code>[[Class]]</code> property, which for Objects is [object Object]. However, that has changed in ECMAScript 2015 so that tests are performed for other types of object and the default is [object Object], so the object may not be a "plain object", just one that isn't recognised as something else. The specification therefore notes that:</p> <blockquote> <p>"[testing using toString] does not provide a reliable type testing mechanism for other kinds of built-in or program defined objects."</p> </blockquote> <p><a href="http://www.ecma-international.org/ecma-262/6.0/index.html#sec-object.prototype.tostring" rel="noreferrer">http://www.ecma-international.org/ecma-262/6.0/index.html#sec-object.prototype.tostring</a></p> <p>So an updated function that allows for pre–ES5 hosts, objects with a <code>[[Prototype]]</code> of null and other object types that don't have <em>getPrototypeOf</em> (such as <em>null</em>, thanks <a href="https://stackoverflow.com/users/110164/chris-nielsen">Chris Nielsen</a>) is below.</p> <p>Note that there is no way to polyfill <em>getPrototypeOf</em>, so may not be useful if support for older browsers is required (e.g. IE 8 and lower, according to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf#Browser_compatibility" rel="noreferrer">MDN</a>).</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>/* Function to test if an object is a plain object, i.e. is constructed ** by the built-in Object constructor and inherits directly from Object.prototype ** or null. Some built-in objects pass the test, e.g. Math which is a plain object ** and some host or exotic objects may pass also. ** ** @param {} obj - value to test ** @returns {Boolean} true if passes tests, false otherwise */ function isPlainObject(obj) { // Basic check for Type object that's not null if (typeof obj == 'object' &amp;&amp; obj !== null) { // If Object.getPrototypeOf supported, use it if (typeof Object.getPrototypeOf == 'function') { var proto = Object.getPrototypeOf(obj); return proto === Object.prototype || proto === null; } // Otherwise, use internal class // This should be reliable as if getPrototypeOf not supported, is pre-ES5 return Object.prototype.toString.call(obj) == '[object Object]'; } // Not an object return false; } // Tests var data = { 'Host object': document.createElement('div'), 'null' : null, 'new Object' : {}, 'Object.create(null)' : Object.create(null), 'Instance of other object' : (function() {function Foo(){};return new Foo()}()), 'Number primitive ' : 5, 'String primitive ' : 'P', 'Number Object' : new Number(6), 'Built-in Math' : Math }; Object.keys(data).forEach(function(item) { document.write(item + ': ' + isPlainObject(data[item]) + '&lt;br&gt;'); });</code></pre> </div> </div> </p>
6,059,894
How Draw rectangle in WPF?
<p>I need draw rectangle in canvas. I know how to draw. But I did not get to do so would draw on a 360-degree</p> <p>Example. blue, lilac, green they are one and the same rectangle, I changed the color for example Red point is start position rectangle.</p> <p><img src="https://i.stack.imgur.com/z2pmh.jpg" alt="enter image description here"></p> <p><strong>EDIT:</strong></p> <p>My actions:</p> <p>LeftMouseDown in x=50;y=50 (press) MoveMouse to 100;100 - now it works MoveMouse to 30;150 or MoveMouse to 10;10 - Now I can not do this, but I need it</p>
6,060,658
7
4
null
2011-05-19 14:02:10.68 UTC
5
2021-01-18 08:47:18.417 UTC
2011-05-19 14:41:21.837 UTC
null
450,466
null
450,466
null
1
19
c#|wpf
72,988
<p>Unless you need a rotated rectangle I wouldn't bother using transforms. Just set Left and Top to the minimum x and y and width to max-x and height maxy-y.</p> <pre class="lang-xml prettyprint-override"><code>&lt;Canvas x:Name="canvas" MouseDown="Canvas_MouseDown" MouseMove="Canvas_MouseMove" MouseUp="Canvas_MouseUp" Background="Transparent" /&gt; </code></pre> <pre><code>private Point startPoint; private Rectangle rect; private void Canvas_MouseDown(object sender, MouseButtonEventArgs e) { startPoint = e.GetPosition(canvas); rect = new Rectangle { Stroke = Brushes.LightBlue, StrokeThickness = 2 }; Canvas.SetLeft(rect,startPoint.X); Canvas.SetTop(rect,startPoint.Y); canvas.Children.Add(rect); } private void Canvas_MouseMove(object sender, MouseEventArgs e) { if(e.LeftButton == MouseButtonState.Released || rect == null) return; var pos = e.GetPosition(canvas); var x = Math.Min(pos.X, startPoint.X); var y = Math.Min(pos.Y, startPoint.Y); var w = Math.Max(pos.X, startPoint.X) - x; var h = Math.Max(pos.Y, startPoint.Y) - y; rect.Width = w; rect.Height = h; Canvas.SetLeft(rect, x); Canvas.SetTop(rect, y); } private void Canvas_MouseUp(object sender, MouseButtonEventArgs e) { rect = null; } </code></pre>
5,995,433
Removing console window for Glut/FreeGlut/GLFW?
<p>Under Visual C++, I have played around with Glut/FreeGlut/GLFW. It seems that everyone of these projects adds a CMD window by default. I tried removing it going under:</p> <blockquote> <p>Properties->C/C++->Preprocessor->Preprocessor Definitions</p> </blockquote> <p>From here, I remove the _CONSOLE and replace it with _WINDOWS</p> <p>Then I went under:</p> <blockquote> <p>Properties->Linker->System->SubSystem</p> </blockquote> <p>And I set the option to Windows (/SUBSYSTEM:WINDOWS)</p> <p>Then when I try compiling under GLFW, I get the following building errors:</p> <ul> <li><p>Error 1 error LNK2001: unresolved external symbol _WinMain@16 MSVCRT.lib</p></li> <li><p>Error 2 fatal error LNK1120: 1 unresolved externals glfwWindow.exe</p></li> </ul> <p>Is it possible to remove the console window?</p>
5,995,512
8
0
null
2011-05-13 17:10:51.067 UTC
9
2017-10-17 19:06:05.963 UTC
2011-05-13 18:21:18.663 UTC
null
422,382
null
422,382
null
1
14
c++|configuration|glut|freeglut|glfw
16,380
<p>Non-console Windows applications use the <code>WinMain()</code> entry point convention. Your Glut examples probably use the standard C <code>main()</code> convention.</p> <p>If you want a quick fix just for the demo app, the WinAPI function <code>FreeConsole()</code> might help.</p> <p>MSDN: <a href="http://msdn.microsoft.com/en-us/library/ms683150(v=vs.85).aspx">http://msdn.microsoft.com/en-us/library/ms683150(v=vs.85).aspx</a></p>
5,598,743
Finding element's position relative to the document
<p>What's the easiest way to determine an elements position relative to the document/body/browser window? </p> <p>Right now I'm using <code>.offsetLeft/offsetTop</code>, but this method only gives you the position relative to the parent element, so you need to determine how many parents to the body element, to know the position relaltive to the body/browser window/document position. </p> <p>This method is also to cumbersome.</p>
5,598,797
9
0
null
2011-04-08 17:37:11.63 UTC
35
2018-09-10 21:27:44.547 UTC
2018-03-21 12:17:53.66 UTC
null
555,121
null
449,132
null
1
150
javascript|dom
169,180
<p>You can traverse the <code>offsetParent</code> up to the top level of the DOM.</p> <pre><code>function getOffsetLeft( elem ) { var offsetLeft = 0; do { if ( !isNaN( elem.offsetLeft ) ) { offsetLeft += elem.offsetLeft; } } while( elem = elem.offsetParent ); return offsetLeft; } </code></pre>
5,612,336
TOGAF 9: difference between enterprise continuum and architecture repository
<p>I am trying to understand the core concepts of TOGAF 9.</p> <p>No matter how often I read the explanation in the TOGAF manual, I don't understand the differences and the relationship between the Enterprise Continuum and the Architecture Repository.</p> <hr /> <p>Some quotes from the documentation:</p> <p><em>Enterprise Continuum</em></p> <blockquote> <p>&quot;The simplest way of thinking of the Enterprise Continuum is as a view of the repository of all the architecture assets. It can contain architecture descriptions, models, building blocks, patterns, viewpoints, and other artifacts&quot;</p> <p>&quot;The Enterprise Continuum provides a valuable context for understanding architectural models: it shows building blocks and their relationships to each other, and the constraints and requirements on a cycle of architecture development.&quot; (pages 565 and 48)</p> </blockquote> <p><em>Architecture Repository</em></p> <blockquote> <p>&quot;This section of TOGAF provides a structural framework for an Architecture Repository that allows an enterprise to distinguish between different types of architectural assets that exist at different levels of abstraction in the organization.&quot; (page 593)</p> </blockquote> <p><strong>Assumptions</strong></p> <p>The samples/template-package of TOGAF contains a word document <em>&quot;TOGAF 9 Template - Architecture Repository.doc&quot;</em>, so</p> <p><strong>1)</strong> I think of the architecture repository as a large document, containing all outputs of all projects related to the architecture.</p> <p><strong>2)</strong> The enterprise continuum is another document classifying the contents of the architecture repository from foundation architecture to organization architecture and providing information about the relationship between these objects.</p> <hr /> <p>What is the difference/relationship between the enterprise continuum and the architecture repository?</p>
5,946,740
10
0
null
2011-04-10 14:16:28.72 UTC
11
2020-07-09 11:34:35.3 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
271,509
null
1
14
architecture|togaf
19,675
<p>The architecture repository is the content - all your designs, policies, frameworks etc.</p> <p>The continuum is the means by which you classify them. It's not just where something is in terms of foundation->organisation. It covers everything, so as per above you will have classifications of 3rd party frameworks, business principles, Technical Standards, all those things too that are present in your enterprise.</p> <p>Within the EC exists the Architecture Continuum and the Solutions Continuum. THis is where you classify your ABB's and SBB's according to the Foundation, CSA, Industry, and Organisation tiers.</p>
17,883,088
Sending mail using Outlook where the Send method fails
<p>I use this code to send email from Excel:</p> <pre><code>Sub Mail_workbook_Outlook_1() 'Working in Excel 2000-2013 'This example send the last saved version of the Activeworkbook 'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm Dim OutApp As Object Dim OutMail As Object Set OutApp = CreateObject("Outlook.Application") Set OutMail = OutApp.CreateItem(0) On Error Resume Next With OutMail .to = "ron@debruin.nl" .CC = "" .BCC = "" .Subject = "This is the Subject line" .Body = "Hi there" .Attachments.Add ActiveWorkbook.FullName 'You can add other files also like this '.Attachments.Add ("C:\test.txt") .Send ' &lt;--------------------------------This is causing troubble End With On Error GoTo 0 Set OutMail = Nothing Set OutApp = Nothing End Sub </code></pre> <p>The problem is that <code>.Send</code> is not recognized as an object (or method).</p> <p>Other commands are working (i.e. Display, Save).</p> <p>I believe this error exists because of security systems at my work. I have even tried using CDO and it is not working ether.</p>
18,549,400
2
17
null
2013-07-26 13:48:57.84 UTC
5
2020-06-23 08:13:30.053 UTC
2020-06-23 08:13:30.053 UTC
null
100,297
null
900,271
null
1
5
excel|vba|email|outlook
56,844
<p>Change <code>.Send</code> to <code>.Display</code> and put <code>SendKeys "^{ENTER}"</code> before the <code>With OutMail</code> line.</p>
19,753,910
Behaviour of imeOptions, imeActionId and imeActionLabel
<p>I'm quite new to Android native development, and I'm trying to figure out how to customize the IME action buttons. I've looked at the Google documentation, but I can find very few information about the expected behaviour.</p> <p>From the <a href="http://developer.android.com/guide/topics/ui/controls/text.html">offical guide</a> I understand that the keyboard action button can be configured using the attributes:</p> <ul> <li><strong>android:imeOptions</strong> can set the text/id of the button displayed near the space key to some pre-defined values (E.g. actionGo set the key label to <em>Go</em> and the id to 2)</li> <li><strong>android:imeActionLabel</strong> set the label of the button displayed inside the input area when the keyboard is fullscreen, usually in landscape mode. Can be set to any string value.</li> <li><strong>android:imeActionId</strong> same as previous but set the numeric Id passed to the callback method</li> </ul> <p>But after some empiric attempts I've found different behaviour between API level 15 and next API levels.</p> <p>I've set up a simple EditText element with the following attributes:</p> <pre><code>&lt;EditText ... android:imeOptions="actionGo" android:imeActionLabel="Custom" android:imeActionId="666" android:inputType="text"/&gt; </code></pre> <p>and I've checked the effect with the different API levels both in portrait and landscape mode. Here is the outcome.</p> <p><strong>API level 15 - 4.0.3</strong></p> <p>In portrait mode the key label is <em>Go</em> and the action id passed to the callback method is 2, accordingly to the imeOptions setting.</p> <p>In landscape mode the key label/id is <em>Go</em>/2 as the portrait mode, while the button displayed in the input area is <em>Custom</em>/666, accordingly to the imeActionLabel and imeActionId attributes.</p> <p><strong>API level 16, 17 and 18 - 4.1.2, 4.2.2 and 4.3</strong></p> <p>Both in portrait and landscape mode the key and the button are displayed with <em>Custom</em> label and are bound to 666 id, ignoring imeOptions attribute.</p> <p>This mismatch in the behaviour is quite annoying because:</p> <ul> <li>with API level >= 16 you can't distinguish between key button and input area button</li> <li>with API level = 15 you can't set any custom text for key button.</li> </ul> <p>Do you know how to obtain this both in API 15 and 16+? Or if there is a way to obtain a consistent behaviour across all (or at least a part of) the API versions?</p> <p>Maybe I am missing something in the IME settings that can justify the different behaviour...</p> <p>Thank you very much!</p>
22,935,932
4
0
null
2013-11-03 14:15:46.863 UTC
7
2017-03-08 21:59:04.613 UTC
null
null
null
null
2,141,516
null
1
47
android|android-input-method
46,881
<p>It's actually up to the input method app, not the Android framework itself, to decide what to do with the values you set.</p> <p>The Android framework just passes the values you set through to the input method, which can then choose what buttons to show on the keyboard or an "extracted" <code>EditText</code> in full-screen view. The Android framework influences the <code>EditorInfo</code> in two ways:-</p> <ul> <li><p>It passes it through <a href="http://developer.android.com/reference/android/view/inputmethod/EditorInfo.html#makeCompatible%28int%29" rel="noreferrer"><code>EditorInfo.makeCompatible</code></a> to ensure the values therein are compatible between the keyboard's and the app's <code>targetApiVersion</code>s. At the moment this only affects some <code>InputType</code> values, not the editor action, but this could change if new editor actions (or completely new settings) are introduced.</p></li> <li><p>It sets the <strong>default</strong> behaviour for the input method, including the behaviour around full-screen editors. If the input method chooses not to override this default behaviour, then it could end up with behaviour that's different between Android versions. Many keyboards do choose to set their own behaviour, in a way that's consistent between Android versions.</p></li> </ul> <p>For that reason, it's not so simple to say that a certain <code>EditorInfo</code> field has a certain effect on any given version, and there's no way to ensure a consistent behaviour, even on one Android version. All you're doing is providing hints to the input method, which chooses how to present them to the user.</p>
38,428,196
How can I get the last/end offset of a kafka topic partition?
<p>I'm writing a <code>kafka</code> consumer using Java. I want to keep the real time of the message, so if there are too many messages waiting for consuming, such as 1000 or more, I should abandon the unconsumed messages and start consuming from the last offset.</p> <p>For this problem, I try to compare the last committed offset and the end offset of a topic(only 1 partition), if the difference between these two offsets is larger than a certain amount, I will set the last committed offset of the topic as next offset so that I can abandon those redundant messages.</p> <p>Now my problem is how to get the end offset of a topic, some people say I can use old consumer, but it's too complicated, do new consumer has this function?</p>
38,448,775
6
0
null
2016-07-18 03:31:54.81 UTC
12
2020-07-09 20:13:01.21 UTC
2020-06-19 18:48:17.373 UTC
null
3,107,798
null
6,601,575
null
1
42
java|apache-kafka|kafka-consumer-api
99,103
<p>The new consumer is also complicated.</p> <p><code>//assign the topic consumer.assign();</code></p> <p><code>//seek to end of the topic consumer.seekToEnd();</code></p> <p><code>//the position is the latest offset consumer.position();</code></p>
26,553,578
Using pop for removing element from 2D array
<p>In the below random array:</p> <pre><code>a = [[1,2,3,4], [6,7,8,9]] </code></pre> <p>Could you please tell me how to remove element at a specific position. For example, how would I remove <code>a[1][3]</code>?</p> <p>I understand <code>list.pop</code> is used for only list type DS here.</p>
26,553,609
4
0
null
2014-10-24 17:57:43.247 UTC
null
2020-05-18 06:15:51.193 UTC
2014-10-24 18:01:20.847 UTC
user2555451
null
null
3,970,193
null
1
5
python|list
38,953
<p>Simple, just pop on the list item.</p> <pre><code>&gt;&gt;&gt; a = [[1,2,3,4], [6,7,8,9]] &gt;&gt;&gt; a[1].pop(3) &gt;&gt;&gt; a [[1, 2, 3, 4], [6, 7, 8]] </code></pre>
27,861,720
How to set default php.ini to be used, OSX Yosemite
<p>I set up a new environment using OSX Yosemite.</p> <p>I'm using the built-in PHP.</p> <p>I'd like to change some config in php.ini such as date.timezone but none of the modifications are working despite restarting the apache server (sudo apachectl restart).</p> <p>phpinfo() is giving a different path than php --ini command.</p> <p>phpinfo():</p> <blockquote> <p>Configuration File (php.ini) Path /usr/local/php5/lib</p> <p>Loaded Configuration File /usr/local/php5/lib/php.ini</p> </blockquote> <p>Via commands :</p> <blockquote> <p>which php</p> <p>/usr/bin/php</p> <p>php --ini</p> <p>Configuration File (php.ini) Path: /etc</p> <p>Loaded Configuration File: /etc/php.ini</p> <p>Scan for additional .ini files in: /Library/Server/Web/Config/php</p> <p>Additional .ini files parsed: (none)</p> </blockquote> <p>So I guess I have to tell somewhere where I should set the default php.ini to be used.</p> <p>Any ideas, hints?</p>
28,515,549
4
0
null
2015-01-09 13:31:58.773 UTC
9
2020-05-10 06:12:06.307 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
3,204,919
null
1
17
php|macos|apache
46,498
<p>move the configuration file to the right spot and update the timezone.</p> <pre><code>$ sudo cp /etc/php.ini.default /etc/php.ini </code></pre> <p>Open the config file /etc/php.ini, find the line that sets your timezone and update it correspondingly.</p> <pre><code>date.timezone = Europe/Berlin </code></pre> <p>Do not forget to remove the ; at the beginning. Restart the Apache server to have PHP load the new .ini file.</p> <pre><code>sudo apachectl restart </code></pre>
43,014,993
Don't know how to build task 'start' when run 'cap production deploy' for capistrano 3.8.0 with Rails
<p>I tried to deploy my rails site using capistrano. So when i ran</p> <pre><code>cap production deploy </code></pre> <p>This is what i got </p> <pre><code>(Backtrace restricted to imported tasks) cap aborted! Don't know how to build task 'start' (see --tasks) Tasks: TOP =&gt; production </code></pre> <p>This is my cap file </p> <pre><code># Load DSL and Setup Up Stages require 'capistrano/setup' require 'capistrano/deploy' require 'capistrano/rails' require 'capistrano/bundler' require 'capistrano/rvm' require 'capistrano/puma' require 'capistrano/scm/git' install_plugin Capistrano::SCM::Git # Loads custom tasks from `lib/capistrano/tasks' if you have any defined. Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r } </code></pre> <p>This is my deploy.rb</p> <pre><code>set :repo_url, 'xxx' set :application, 'xxx' set :user, 'yyy' set :puma_threads, [4, 16] set :puma_workers, 0 set :pty, true set :use_sudo, false set :stages, ["staging", "production"] set :default_stage, "production" set :deploy_via, :remote_cache set :deploy_to, "/home/#{fetch(:user)}/apps/#{fetch(:application)}" set :puma_bind, "unix://#{shared_path}/tmp/sockets/#{fetch(:application)}-puma.sock" set :puma_state, "#{shared_path}/tmp/pids/puma.state" set :puma_pid, "#{shared_path}/tmp/pids/puma.pid" set :puma_access_log, "#{release_path}/log/puma.error.log" set :puma_error_log, "#{release_path}/log/puma.access.log" set :ssh_options, { forward_agent: true, user: fetch(:user), keys: %w(~/.ssh/id_rsa) } set :puma_preload_app, true set :puma_worker_timeout, nil set :puma_init_active_record, true # Change to false when not using ActiveRecord namespace :puma do desc 'Create Directories for Puma Pids and Socket' task :make_dirs do on roles(:app) do execute "mkdir #{shared_path}/tmp/sockets -p" execute "mkdir #{shared_path}/tmp/pids -p" end end before :start, :make_dirs end namespace :deploy do desc "Make sure local git is in sync with remote." task :check_revision do on roles(:app) do unless `git rev-parse HEAD` == `git rev-parse origin/master` puts "WARNING: HEAD is not the same as origin/master" puts "Run `git push` to sync changes." exit end end end desc 'Initial Deploy' task :initial do on roles(:app) do before 'deploy:restart', 'puma:start' invoke 'deploy' end end desc 'Restart application' task :restart do on roles(:app), in: :sequence, wait: 5 do invoke 'puma:restart' end end before :starting, :check_revision after :finishing, :compile_assets after :finishing, :cleanup end </code></pre> <p>So the code above is working before but when i update my gems then i can not deploy my app anymore.</p> <p>So how can i fix this?</p> <p>Thanks!</p>
43,021,458
3
0
null
2017-03-25 09:59:41.55 UTC
11
2021-05-18 17:07:23.68 UTC
null
null
null
null
3,403,614
null
1
36
ruby-on-rails|capistrano
16,772
<p>Add <code>install_plugin Capistrano::Puma</code> into your <strong>Capfile</strong> after <code>require 'capistrano/puma'</code>.</p> <p><code>capistrano3-puma</code> moved to 3.0 a few days ago. This line is required for loading default puma tasks in this version.</p> <p>See <a href="https://github.com/seuros/capistrano-puma#usage" rel="noreferrer">https://github.com/seuros/capistrano-puma#usage</a></p>
25,297,489
Accept HTTP Request in R shiny application
<p>I have a shiny app that I have made that needs to get its data from another server, i.e. the other server when the shiny app is opened sends a request to the shiny app to open the app and feed it the data that it needs.</p> <p>To simulate this I can send the following to the R shiny app when I open the app in firefox:</p> <pre><code> http://localhost:3838/benchmark-module/?transformerData=data/TransformerDataSampleForShiny.json </code></pre> <p>This is a simple get request that sends the sting called : "Transformer Data" with contents "data/TransformerDataSampleForShing.json" to the shiny app.</p> <p>When I use the code it works fine:</p> <pre><code>#(Abridged code, I am only showing the start of the code) shinyServer(function(input, output) { jsonFile &lt;- "data/TransformerDataSampleForShiny.json" JSONdata &lt;- fromJSON(jsonFile) </code></pre> <p>but when I want to do the exact same thing except rather than hard coding the string "data/TransformerDataSampleForShiny.json" i want to receive that string from the http request above. How do I do this?? I have tried the code:</p> <pre><code>shinyServer(function(input, output) { jsonFile &lt;- input$transformerData JSONdata &lt;- fromJSON(jsonFile) </code></pre> <p>and I have also tried:</p> <pre><code>.... jsonFile &lt;- input$TransformerData </code></pre> <p>but none of these have worked.</p> <p>SO the main question is, is how do I code to recieve HTTP requests? I would like to receive strings from HTTP GET requests and or JSON files from POST requests.</p> <p>Just to clarify I DONT want to send post or get requests from R. I want to receive them. I can't use the httr package or the httpRequest package for receiving</p> <p>Thanks so much!</p>
25,297,636
4
1
null
2014-08-13 22:50:37.257 UTC
25
2021-10-16 06:08:22.073 UTC
null
null
null
null
3,814,836
null
1
24
r|shiny|shiny-server
15,396
<p>You can receive GET requests using <code>session$clientData</code>. An example run the following </p> <pre><code>library(shiny) runApp(list( ui = bootstrapPage( textOutput('text') ), server = function(input, output, session) { output$text &lt;- renderText({ query &lt;- parseQueryString(session$clientData$url_search) paste(names(query), query, sep = "=", collapse=", ") }) } ), port = 5678, launch.browser = FALSE) </code></pre> <p>and navigate to </p> <pre><code>http://127.0.0.1:5678/?transformerData=data/TransformerDataSampleForShiny.json </code></pre> <p>See @Xin Yin answer for a method to expose POST requests.</p>
25,145,609
How to return a Json object from a C# method
<p>I am trying to fix an ASP.NET WebAPI method where a Json response is required. However it's returning a string instead.</p> <p>Initially it was returing XML format, but I've added this line to the mvc code in App_Start\WebApiConfig.cs in order to return Json by default. </p> <pre><code>config.Formatters.Remove(config.Formatters.XmlFormatter); </code></pre> <p>We've updated the c# method as follows to use NewtonSoft:</p> <pre><code>public string Get() { string userid = UrlUtil.getParam(this, "userid", ""); string pwd = UrlUtil.getParam(this, "pwd", ""); string resp = DynAggrClientAPI.openSession(userid, pwd); JsonSerializer ser = new JsonSerializer(); string jsonresp = JsonConvert.SerializeObject(resp); return resp; } </code></pre> <p>The resp var is coming back as a string type:</p> <pre><code>"{status:\"SUCCESS\",data:[\"4eb97d2c6729df98206cf214874ac1757649839fe4e24c51d21d\"]}" </code></pre> <p>and jsonresp var looks like this :</p> <pre><code>"\"{status:\\\"SUCCESS\\\",data:[\\\"4eb97d2c6729df98206cf214874ac1757649839fe4e24c51d21d\\\"]}\"" </code></pre> <p>and in Chrome's F12 dev tools, the data object is :</p> <pre><code>""{status:\"SUCCESS\",data:[\"4eb97d2c6729df98206cf214874ac1757649839fe4e24c51d21d\"]}"" </code></pre> <p>and in Console tools, the result of angular.fromJson(data) :</p> <pre><code>"{status:"SUCCESS",data:["4eb97d2c6729df98206cf214874ac1757649839fe4e24c51d21d"]}" </code></pre> <p>I would appreciate some advice on how to properly return the Json object, and NOT in any string type.</p> <hr> <h3>UPDATE</h3> <p>By intercepting the <code>resp</code> var, and using Mr. Chu's suggestion below, I can successfully achieve a nice clean Json object on the client. The key is that <code>resp</code> needs to contains double quotes around both key:value pairs:</p> <pre><code>public HttpResponseMessage Get() { string userid = UrlUtil.getParam(this, "userid", ""); string pwd = UrlUtil.getParam(this, "pwd", ""); string resp = DynAggrClientAPI.openSession(userid, pwd); resp = "{\"status\":\"SUCCESS\",\"data\":[\"194f66366a6dee8738428bf1d730691a9babb77920ec9dfa06cf\"]}"; // TEST !!!!! var response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(resp, System.Text.Encoding.UTF8, "application/json"); return response; } </code></pre> <p>in Chrome console, the response is :</p> <pre><code>Object {status: "SUCCESS", data: Array[1]} data: Array[1] status: "SUCCESS" __proto__: Object </code></pre>
25,146,052
5
2
null
2014-08-05 18:12:14.21 UTC
7
2022-09-14 09:27:46.707 UTC
2019-08-31 22:01:45.333 UTC
null
7,911,776
null
1,472,806
null
1
25
c#|asp.net-web-api|json.net
126,223
<p><code>resp</code> is already a JSON string, but it is not valid JSON (the keys are not wrapped in quotes (<code>"</code>). If it is returned to angular, the JavaScript JSON.parse() method is unable to deserialize it. However, you can use JSON.NET in deserialize it to a JObject and serialize it again into valid JSON and create your own <code>HttpResponseMessage</code>...</p> <pre><code>public HttpResponseMessage Get() { string userid = UrlUtil.getParam(this, "userid", ""); string pwd = UrlUtil.getParam(this, "pwd", "" ); string resp = DynAggrClientAPI.openSession(userid, pwd); var jObject = JObject.Parse(resp); var response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(jObject.ToString(), Encoding.UTF8, "application/json"); return response; } </code></pre> <p>Or you can just return the <code>JObject</code> and have Web API serialize it for you...</p> <pre><code>public JObject Get() { string userid = UrlUtil.getParam(this, "userid", ""); string pwd = UrlUtil.getParam(this, "pwd", "" ); string resp = DynAggrClientAPI.openSession(userid, pwd); var jObject = JObject.Parse(resp); return jObject; } </code></pre> <p>In either case, the Web API call should return this JSON, which is now valid...</p> <pre><code>{ "status": "SUCCESS", "data": [ "4eb97d2c6729df98206cf214874ac1757649839fe4e24c51d21d" ] } </code></pre> <p>In the angular code, you'd have to dig out the session id which is stored in an array called <code>data</code>...</p> <pre><code>userService.openUserSession(rzEnvJson).then(function (response) { var sessionResponse = response.data; // or simply response, depending if this is a promise returned from $http $rootScope.rgSessionVars.sessionID = sessionResponse.data[0]; }); </code></pre>
27,501,819
How to add a client side pkcs12 certificate to Postman Chrome, W7 ?
<p>I try to test a 'strange' GET request where I have to provide a BASIC authentication and a client side certificate. </p> <p>I try to check it with Postman Chrome but I did not understand how to link the certificate from chrome personal certificate to my request. </p> <p>I saw this discussion : <a href="https://github.com/a85/POSTMan-Chrome-Extension/issues/482" rel="noreferrer">https://github.com/a85/POSTMan-Chrome-Extension/issues/482</a> but it is about MAC keystore and I can't transpose is to W7/Chrome. </p> <p>Here is my java code set up that should do the same job as postman to help you understand what I want postman to do. We use that post to write it </p> <pre><code> InputStream is = context.getResources().getAssets().open("CertificateFile.p12"); KeyStore keyStore = KeyStore.getInstance("PKCS12"); BufferedInputStream bis = new BufferedInputStream(is); String password ="xxxxx"; keyStore.load(bis, password.toCharArray()); // password is the PKCS#12 password. If there is no password, just pass null // Init SSL Context KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509"); kmf.init(keyStore, password.toCharArray()); KeyManager[] keyManagers = kmf.getKeyManagers(); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, null, null); HttpsURLConnection urlConnection = null; String strURL = "theUrlITryToHit"; url = new URL(strURL); urlConnection = (HttpsURLConnection) url.openConnection(); if(urlConnection instanceof HttpsURLConnection) { ((HttpsURLConnection)urlConnection) .setSSLSocketFactory(sslContext.getSocketFactory()); } urlConnection.setRequestMethod("GET"); String basicAuth = "Basic " + Base64.encodeToString("pseudo:password".getBytes(), Base64.NO_WRAP); urlConnection.setRequestProperty ("Authorization", basicAuth); </code></pre>
29,830,140
2
1
null
2014-12-16 09:53:30.18 UTC
7
2019-09-03 16:42:45.96 UTC
null
null
null
null
1,959,005
null
1
14
java|android|google-chrome|ssl|postman
45,818
<p>I was having a similar issue and just got it working. My private key and cert were stored in a .pem file, so I first needed to put them in to a format that Windows would use. I did that with the following command:</p> <pre><code>openssl pkcs12 -inkey mycertandkey.pem -in mycert.crt -export -out mycertandkey.pfx </code></pre> <p>I did this in linux but it should work in Windows as well, if you have openssl installed. </p> <p>Run <code>certmgr.msc</code> in Windows. Right-click the 'Personal' folder and select 'All tasks' -> 'Import...' and choose the .pfx file. Enter the passphrase and import it in to the 'Personal' folder.</p> <p>Once that's done, you'll need to close your running Chrome windows. Then open Postman in a new window. When you attempt to connect to the URL, this time it should ask to confirm the use of the client cert. Once confirmed, you should be able to make calls to the URL from then on.</p>
21,733,856
python: Is there a downside to using faulthandler?
<p>Python 3.3 includes a module named <code>faulthandler</code> that displays helpful traceback information if a segfault occurs. (For Python versions prior to 3.3, the module can be <a href="https://pypi.python.org/pypi/faulthandler/">obtained from PyPI</a>.)</p> <p>The module is not enabled by default. It is enabled like this:</p> <pre><code>import faulthandler faulthandler.enable() </code></pre> <p>This feature is very useful. Is there any particular reason it isn't enabled by default? Does it have any negative effects on performance?</p>
29,246,977
1
1
null
2014-02-12 16:34:11.763 UTC
7
2020-07-02 11:50:16.49 UTC
2020-07-02 11:50:16.49 UTC
null
6,573,902
null
162,094
null
1
31
python|python-3.x|python-3.3|traceback|faulthandler
7,906
<blockquote> <p>This feature is very useful. Is there any particular reason it isn't enabled by default? Does it have any negative effects on performance?</p> </blockquote> <p>The reason is that faulthandler remembers the file descriptor of stderr, usually fd 2. The problem is that fd 2 may become something else, like a socket, a pipe, an important file, etc. There is no reliable way to detect this situation, and so it's safer to not enable faulthandler by default in Python.</p> <p>faulthandler is safe in almost all cases, except when a file descriptor stored by faulthandler is replaced. Problem also described in the doc: <a href="https://docs.python.org/dev/library/faulthandler.html#issue-with-file-descriptors">https://docs.python.org/dev/library/faulthandler.html#issue-with-file-descriptors</a></p> <p>Note: I wrote faulthandler.</p>
51,489,904
Angular 6, should I put secret environment variables in environment.ts file?
<p>There are two sub-questions:</p> <ol> <li><p>Should I put secret environment variables in the <code>environment.ts</code> file?</p> </li> <li><p>The <code>process</code> variable shim is gone. If I use it, <code>tsc</code> will throw an error: <code>Cannot find name 'process'</code>.</p> </li> </ol> <p>Here is my thing:</p> <p>About Q1: I don't think put secret environment variables in environment.ts file is correct. Because these files will be a push to source code management, like GitHub, GitLab, bitbucket. It's not safe. So I think secret environment variables should be passed through <code>process.env</code>, like <code>process.env.ACCESS_TOKEN</code>, or, if use docker-compose, should put the secret environment variables in <code>.env</code> file and add this file to <code>.gitignore</code> file.</p> <p>About Q2: If I use Heroku to set up my environment variables, it depends on the <code>process</code> variable. Now, angular6 get rid of the shim of <code>process</code>, How can I work with Heroku? Also, using docker-compose pass environment variables through <code>.env</code> file depends on <code>process</code> too.</p> <p>And if use <code>.env</code> file for docker-compose, there is a new question come out: <a href="https://stackoverflow.com/questions/51355142/how-to-pass-variables-in-env-file-to-angular6-environment-ts-file">How to pass variables in .env file to angular6 environment.ts file</a></p> <p><strong>update 1:</strong></p> <p>Here is a case:</p> <p>First, <strong>there is no back-end</strong></p> <p>I use GitHub API and another open API, and there is an environment variable named <code>access_token</code>, If I put this in the <code>environment.ts</code> file and push my front-end source code to Github, Github will detect the secret information and give me a warning, they say:</p> <blockquote> <p>You should not put the GitHub access token in your source code and push it to repo, so they will revoke my access token.</p> </blockquote> <p>So I want to use <code>process.env.ACCESS_TOKEN</code>, but the <code>process</code> variable shim is gone in <code>Angular6</code>, how can I solve this? Should I add <code>environment.ts</code> file to the <code>.gitignore</code> file or what?</p> <p><strong>update 2</strong></p> <p>Here is another case</p> <p>Continue with update 1. Now, I add <code>docker-compose.yaml</code> and <code>Dockerfile</code> to run my front-end app in the <code>docker</code> container.</p> <p>Here is the workflow:</p> <ol> <li><p>Write <code>Dockerfile</code>, run <code>npm run build</code> command and copy <code>./build</code> directory to <code>nginx</code> static file directory of <code>docker</code> container. the <code>./build</code> directory contains <code>index.html</code>, <code>bundle.js</code> file and so on.</p> </li> <li><p>Put <code>access_token</code> and other secret environment variables into <code>.env</code> file.</p> </li> <li><p>Run <code>docker-compose up</code> to run my app in a <code>docker</code> container.</p> </li> </ol> <p>I think this workflow is solid. No need back-end service, the secret environment variables in <code>.env</code> and <code>.gitignore</code> contains <code>.env</code> file, so it will not be pushed to Github repo.</p> <p>But, the key point is <code>process</code> shim is gone. I can't get environment variables through <code>process</code>.</p> <p><strong>update 3</strong></p> <p>I think my question focus on <strong>front-end app development phase</strong>. I continue to use above case to explain.</p> <p>For production ready, the workflow is:</p> <ol> <li><p>Make a back-end service for github oauth, when the oauth workflow is done. Back-end service send <code>access_token</code> to front-end.</p> </li> <li><p>front-end login successfully, get the <code>access_token</code> from back-end service and store it in localStorage or cookie. Don't need get <code>access_token</code> from <code>process.env</code></p> </li> </ol> <p>But for development phase, Front-end and back-end development are separated for the general situation. So, Front-end should not depend on the back-end service.</p> <p>And I don't want to build the whole big system for the beginning.</p> <p>So I think the question is:</p> <p>Where to store secret environment variables and how to get within <code>Angular6</code> front-end application code? Several situations need to be considered:</p> <ul> <li>Work with PaaS Heroku config vars</li> <li>Dockerized(docker-compose, Dockerfile), <code>.env</code> file.</li> <li>Without back-end service.</li> <li>Add the environment variables file to <code>.gitignore</code>, don't push to SCM(Github, GitLab and so on)</li> </ul>
51,490,031
1
2
null
2018-07-24 03:07:24.207 UTC
9
2020-12-21 08:07:01.427 UTC
2020-12-21 08:07:01.427 UTC
null
6,463,558
null
6,463,558
null
1
30
angular|angular-cli|angular6|angular-cli-v6
23,403
<p><strong>TL; DR</strong></p> <p>You should not treat <code>environment.ts</code> as something similar to <code>process.env</code>. </p> <p>The name is similar but the behaviour is absolutely not. All the settings from <code>environment.ts</code> will directly go to your code. That's why it is not secure to put secrets to <code>environments.ts</code> in any way.</p> <p>The browser alternatives to environment variables (<code>process.env</code>) are </p> <ul> <li>sessionStorage: behaves like <code>export VAR=value</code></li> <li>localStorage: behaves like <code>export VAR=value</code> but put into your <code>.bash_profile</code> and is persistent across sessions</li> <li>indexedDB: same as localStorage with only difference its <strong>asynchronous</strong></li> <li>cookies: does not really look like <code>process.env</code>, but still in some cases can send the secrets automatically to some backends</li> <li>backend: it is always an option to get secrets from backend, <strong>asynchronous</strong></li> </ul> <p><strong>Long version</strong></p> <p>There is no such a thing as a secret in the client side application. Since your code in the browser will be able to get those variables, everybody will be able to get those variables in the runtime.</p> <p>That means, all libraries you explicitly or implicitly use, user's browser extensions and anybody who is able to sniff your / your user's traffic - all they will get your secrets quite easily.</p> <p>It does not matter how you pass it. Through process.env or environment.ts, all will end up in the generated main.js file where they are so much not secret anymore that the furhter discussion is actually useless.</p> <p><strong>Answer to updated part 1:</strong></p> <p>If <code>access_token</code> is your (or your synthetic user) token, then you have two options:</p> <ol> <li>Write a backend service that pushes the code on behalf of this Github user. That means the token will be stored in the environment variable on a backend side, which is a very much appropriate way of doing stuff</li> <li>Ask your user to enter the token for every push or ask it once and store it in a localStorage. This make sense only in case when every user has its own / different token</li> </ol> <p><strong>Answer to updated part 2:</strong></p> <p>You can build a docker around your frontend, run it within a kubernetes cluster inside a virtual machine which is hosted on the most secure server in the world, it will not make your token secure if you put it as angular environment variable because what is public cannot be secret.</p> <p>You seem to be not understanding the main point: GitHub gives you an error and does not allow to push the code, you should already be grateful that it finds a problem in your architecture. If you want to solve the problem then use the solutions above. If you want to simply bypass the validation of GitHub and you don't care about the security then simply split your token string into two pieces and store it apart and GitHub will not be able to find it.</p> <p><strong>Answer to updated part 3:</strong></p> <p>You can perform GitHub's Oauth2 requests directly from your frontend. Every of your users should have an account there and that would solve all your problems. That's actually the same what was proposed as a solution #2.</p> <p>If you go with solution #1 with a backend, for development purposes just pre-set up the cookie or use <code>localStorage.setItem('your-token-here')</code>. This is way more than enough for development purposes.</p>
32,806,287
How to call a model function inside the controller in Laravel 5
<p>I have been facing a problem of not able to use the model inside the controller in the new laravel framework version 5. i created the model using the artisan command <strong>"php artisan make:model Authentication"</strong> and it created the model successfully inside the app folder, after that i have created a small function test in it, and my model code looks like this.</p> <pre><code> &lt;?php namespace App; use Illuminate\Database\Eloquent\Model; class Authentication extends Model { protected $table="canteens"; public function test(){ echo "This is a test function"; } } </code></pre> <p>Now i have no idea, that how shall i call the function test() of model to my controller , Any help would be appreciated, Thanks in advance.</p>
32,806,828
8
1
null
2015-09-27 09:08:11.943 UTC
3
2020-02-22 08:33:28.43 UTC
null
null
null
null
4,188,858
null
1
15
php|laravel-5
106,553
<p>A quick and dirty way to run that function and see the output would be to edit <code>app\Http\routes.php</code> and add:</p> <pre><code>use App\Authentication; Route::get('authentication/test', function(){ $auth = new Authentication(); return $auth-&gt;test(); }); </code></pre> <p>Then visit your site and go to this path: <code>/authentication/test</code></p> <p>The first argument to Route::get() sets the path and the second argument says what to do when that path is called.</p> <p>If you wanted to take this further, I would recommend creating a controller and replacing that anonymous function with a reference to a method on the controller. In this case, you would change <code>app\Http\Routes.php</code> by instead adding:</p> <pre><code>Route::get('authentication/test', 'AuthenticationController@test'); </code></pre> <p>And then use artisan to make a controller called <code>AuthenticationController</code> or create <code>app\Http\Controllers\AuthenticationController.php</code> and edit it like so:</p> <pre><code>&lt;?php namespace App\Http\Controllers; use App\Authentication; class AuthenticationController extends Controller { public function test() { $auth = new Authentication(); return $auth-&gt;test(); } } </code></pre> <p>Again, you can see the results by going to <code>/authentication/test</code> on your Laravel site.</p>