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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
40,020,703 | Angular2 - Redirect to calling url after successful login | <p>I have my application up and running with Angular 2.1.0.
The routes are protected via router Guards, canActivate.</p>
<p>When pointing the browser to a protected area like "localhost:8080/customers" I get redirected to my login page just like expected.</p>
<p>But after a successful login, I would like to be redirected back to calling URL ("/customers" in this case). </p>
<p>The code for handling the login looks like this</p>
<pre class="lang-ts prettyprint-override"><code>login(event, username, password) {
event.preventDefault();
var success = this.loginService.login(username, password);
if (success) {
console.log(this.router);
this.router.navigate(['']);
} else {
console.log("Login failed, display error to user");
}
}
</code></pre>
<p>The problem is, I don't know how to get a hold of the calling url from inside the login method.</p>
<p>I did find a question (and answer) regarding this but couldn't really make any sense of it.
<a href="https://stackoverflow.com/questions/36160118/angular2-redirect-after-login">Angular2 Redirect After Login</a></p> | 40,021,645 | 3 | 1 | null | 2016-10-13 12:13:47.01 UTC | 15 | 2020-12-09 09:22:51.09 UTC | 2019-11-04 14:40:38.98 UTC | null | 1,833,602 | null | 2,760,747 | null | 1 | 51 | angular|angular2-routing | 88,625 | <p>There's a tutorial in the Angular Docs, <a href="https://angular.io/guide/router-tutorial-toh#milestone-5-route-guards" rel="noreferrer">Milestone 5: Route guards</a>. One possible way to achieve this is by using your AuthGuard to check for your login status and store the url on your AuthService.</p>
<p><strong>AuthGuard</strong></p>
<pre class="lang-ts prettyprint-override"><code>import { Injectable } from '@angular/core';
import {
CanActivate, Router,
ActivatedRouteSnapshot,
RouterStateSnapshot
} from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let url: string = state.url;
return this.checkLogin(url);
}
checkLogin(url: string): boolean {
if (this.authService.isLoggedIn) { return true; }
// Store the attempted URL for redirecting
this.authService.redirectUrl = url;
// Navigate to the login page with extras
this.router.navigate(['/login']);
return false;
}
}
</code></pre>
<p><strong>AuthService</strong> or your LoginService</p>
<pre class="lang-ts prettyprint-override"><code>import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Router } from '@angular/router';
@Injectable()
export class AuthService {
isLoggedIn: boolean = false;
// store the URL so we can redirect after logging in
public redirectUrl: string;
constructor (
private http: Http,
private router: Router
) {}
login(username, password): Observable<boolean> {
const body = {
username,
password
};
return this.http.post('api/login', JSON.stringify(body)).map((res: Response) => {
// do whatever with your response
this.isLoggedIn = true;
if (this.redirectUrl) {
this.router.navigate([this.redirectUrl]);
this.redirectUrl = null;
}
}
}
logout(): void {
this.isLoggedIn = false;
}
}
</code></pre>
<p>I think this will give an idea how things work, of course you probably need to adapt to your code</p> |
10,826,014 | Suppress some warnings in SQL Server SSDT | <p>In <a href="http://msdn.microsoft.com/en-us/library/hh272686">SQL Server Data Tools</a>, I would like to suppress some, but not all, occurrences of SQL71502 ("--- has an unresolved reference to object ---"). I know I can suppress through Project Properties, Build, Suppress Transact-SQL warnings, but this will globally suppress. Can this be done?</p> | 10,854,815 | 5 | 0 | null | 2012-05-31 00:27:47.64 UTC | 4 | 2015-02-09 11:13:29.35 UTC | 2012-05-31 00:34:00.84 UTC | null | 261,997 | null | 14,280 | null | 1 | 34 | sql-server|sql-server-data-tools | 20,162 | <p>You weren't clear on what would determine which 71502 messages would be suppressed and which ones wouldn't but based on my own understanding and research I think the answer is the same. In short, no. </p>
<p>You can suppress all warnings, or warnings based on a specific code ( 71502 ) but that is as granular as it gets.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/hh272681(v=VS.103).aspx">http://msdn.microsoft.com/en-us/library/hh272681(v=VS.103).aspx</a></p>
<p>This link talks about promoting warning to errors but also demonstrates how the suppress filter is used - which based on your question you probably already know.</p>
<p><a href="http://social.msdn.microsoft.com/Forums/is/ssdt/thread/9b698de1-9f6d-4e51-8c73-93c57355e768">http://social.msdn.microsoft.com/Forums/is/ssdt/thread/9b698de1-9f6d-4e51-8c73-93c57355e768</a></p> |
10,772,598 | Vim select the ends of multiple lines (block mode, but where the ending column varies) | <p>Is there any way in vim that I can select the end of all these lines? (I'm only showing the end of the lines in these screenshots).</p>
<p>In block mode I can get them all if the bottom line is longer than the rest, but if the bottom line is shorter, the longer lines are truncated.</p>
<p>EDIT | I guess I can just pad out the bottom line with spaces before I select, then delete the spaces later.</p>
<p><img src="https://i.stack.imgur.com/5287U.png" alt="enter image description here">
<img src="https://i.stack.imgur.com/XSCFp.png" alt="enter image description here"></p> | 10,772,658 | 5 | 0 | null | 2012-05-27 08:15:59.75 UTC | 16 | 2022-09-15 18:02:42.063 UTC | null | null | null | null | 322,122 | null | 1 | 39 | vim | 19,954 | <ol>
<li>Put your cursor on the top-left character you want to be part of the block.</li>
<li>Enter block selection mode with <kbd>ctrl</kbd>+<kbd>v</kbd></li>
<li><strong>Select to the end of the line with <kbd>$</kbd></strong> (this is the step you're missing; if you move to the end of the first line using <kbd>$</kbd> then the selection will extend to the end of subsequent lines as well)</li>
<li>Move down 3 lines with <kbd>3</kbd><kbd>j</kbd></li>
</ol>
<p>There's more information in the Vim documentation's section on visual mode which you can <a href="http://vimdoc.sourceforge.net/htmldoc/visual.html#v_%24">read online</a>, or just type <code>:help v_$</code> in Vim.</p> |
5,931,898 | Persisting & loading metadata in a backbone.js collection | <p>I have a situation using backbone.js where I have a collection of models, and some additional information about the models. For example, imagine that I'm returning a list of amounts: they have a quantity associated with each model. Assume now that the unit for each of the amounts is always the same: say quarts. Then the json object I get back from my service might be something like:</p>
<pre><code>{
dataPoints: [
{quantity: 5 },
{quantity: 10 },
...
],
unit : quarts
}
</code></pre>
<p>Now backbone collections have no real mechanism for natively associating this meta-data with the collection, but it was suggested to me in this question: <a href="https://stackoverflow.com/questions/5930656/setting-attributes-on-a-collection-backbone-js">Setting attributes on a collection - backbone js</a> that I can extend the collection with a <code>.meta(property, [value])</code> style function - which is a great solution. However, naturally it follows that we'd like to be able to cleanly retrieve this data from a json response like the one we have above.</p>
<p>Backbone.js gives us the <code>parse(response)</code> function, which allows us to specify where to extract the collection's list of models from in combination with the <code>url</code> attribute. There is no way that I'm aware of, however, to make a more intelligent function without overloading <code>fetch()</code> which would remove the partial functionality that is already available.</p>
<p>My question is this: is there a better option than overloading <code>fetch()</code> (and trying it to call it's superclass implementation) to achieve what I want to achieve?</p>
<p>Thanks</p> | 5,932,429 | 2 | 0 | null | 2011-05-09 02:25:05.567 UTC | 10 | 2011-05-09 09:12:04.3 UTC | 2017-05-23 10:27:15.82 UTC | null | -1 | null | 488,927 | null | 1 | 14 | javascript|json|collections|backbone.js | 4,854 | <p>Personally, I would wrap the <code>Collection</code> inside another <code>Model</code>, and then override <code>parse</code>, like so:</p>
<pre><code>var DataPointsCollection = Backbone.Collection.extend({ /* etc etc */ });
var CollectionContainer = Backbone.Model.extend({
defaults: {
dataPoints: new DataPointsCollection(),
unit: "quarts"
},
parse: function(obj) {
// update the inner collection
this.get("dataPoints").refresh(obj.dataPoints);
// this mightn't be necessary
delete obj.dataPoints;
return obj;
}
});
</code></pre>
<p>The <code>Collection.refresh()</code> call updates the model with new values. Passing in a custom <code>meta</code> value to the Collection as previously suggested might stop you from being able to bind to those meta values.</p> |
5,910,454 | Encrypt/Decrypt using Bouncy Castle in C# | <p>I am using the "BouncyCastle.Crypto.dll" for encrypt/decrypt a string in my app. I am using the
following <a href="https://web.archive.org/web/20140120123730/http://elian.co.uk/post/2009/07/29/Bouncy-Castle-CSharp.aspx" rel="nofollow noreferrer">code from this blog</a>:</p>
<ol>
<li><p>I have a class BCEngine, exactly the same as the one given in the link mentioned above.</p>
<pre><code>public class BCEngine
{
private readonly Encoding _encoding;
private readonly IBlockCipher _blockCipher;
private PaddedBufferedBlockCipher _cipher;
private IBlockCipherPadding _padding;
public BCEngine(IBlockCipher blockCipher, Encoding encoding)
{
_blockCipher = blockCipher;
_encoding = encoding;
}
public void SetPadding(IBlockCipherPadding padding)
{
if (padding != null)
_padding = padding;
}
public string Encrypt(string plain, string key)
{
byte[] result = BouncyCastleCrypto(true, _encoding.GetBytes(plain), key);
return Convert.ToBase64String(result);
}
public string Decrypt(string cipher, string key)
{
byte[] result = BouncyCastleCrypto(false, Convert.FromBase64String(cipher), key);
return _encoding.GetString(result);
}
/// <summary>
///
/// </summary>
/// <param name="forEncrypt"></param>
/// <param name="input"></param>
/// <param name="key"></param>
/// <returns></returns>
/// <exception cref="CryptoException"></exception>
private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, string key)
{
try
{
_cipher = _padding == null ? new PaddedBufferedBlockCipher(_blockCipher) : new PaddedBufferedBlockCipher(_blockCipher, _padding);
byte[] keyByte = _encoding.GetBytes(key);
_cipher.Init(forEncrypt, new KeyParameter(keyByte));
return _cipher.DoFinal(input);
}
catch (Org.BouncyCastle.Crypto.CryptoException ex)
{
throw new CryptoException(ex.Message);
}
}
}
</code></pre></li>
</ol>
<p>I am using an asp.net form in which i have written code as given below:</p>
<pre><code> public partial class EncryptionForm : System.Web.UI.Page
{
Encoding _encoding;
IBlockCipherPadding _padding;
string key = "DFGFRT";
string textToBeEncrypted = "Original text. Please encrypt me.";
string txtEncryptedText = string.empty;
string txtDecryptedText = string.empty;
protected void Page_Load(object sender, EventArgs e)
{
_encoding = Encoding.ASCII;
Pkcs7Padding pkcs = new Pkcs7Padding();
_padding = pkcs;
}
protected void btnEncrypt_Click(object sender, EventArgs e)
{
txtEncryptedText = AESEncryption(textToBeEncrypted, key, true);
}
protected void btnDecrypt_Click(object sender, EventArgs e)
{
txtDecryptedText = AESDecryption(txtEncryptedText.Text, key, true);
}
public string AESEncryption(string plain, string key, bool fips)
{
BCEngine bcEngine = new BCEngine(new AesEngine(), _encoding);
bcEngine.SetPadding(_padding);
return bcEngine.Encrypt(plain, key);
}
public string AESDecryption(string cipher, string key, bool fips)
{
BCEngine bcEngine = new BCEngine(new AesEngine(), _encoding);
bcEngine.SetPadding(_padding);
return bcEngine.Decrypt(cipher, key);
}
}
</code></pre>
<p>Not sure, but due to some reason, I get an exception when I call the btnEncrypt_Click</p>
<p>"Key length not 128/192/256 bits."</p>
<p>Can anybody please guide? I am a complete newbie to this.
Thanks in Advance.</p> | 5,910,512 | 2 | 1 | null | 2011-05-06 11:03:58.79 UTC | 4 | 2020-05-09 22:15:18.943 UTC | 2020-05-09 22:15:18.943 UTC | null | 4,449,174 | null | 206,686 | null | 1 | 20 | c#|bouncycastle | 49,064 | <p>Your <code>string key = "DFGFRT";</code> is not 128/192/256 bits. </p>
<p><code>DFGFRT</code> is 6 characters, which is 6 (or 12?) bytes = 8*12 = 96 bits (at most). </p>
<p>To get a 128 bit key you need a 16 byte string, so I'd go on the safe side and use a 16 character string so it will be a 128 bit key if using single byte characters and 256 if using wide characters.</p> |
23,153,822 | Mysql datetime DEFAULT CURRENT_TIMESTAMP error | <p><strong>1.</strong>
When I ran this MYSQL syntax on windows it ran properly:</p>
<pre><code>CREATE TABLE New
(
id bigint NOT NULL AUTO_INCREMENT,
timeUp datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
)
</code></pre>
<p>But when I tried running this code on Linux I got an error:</p>
<pre><code> #1067 - Invalid default value for 'time'
</code></pre>
<p><strong>2.</strong>
On windows the case is not sensitive eg. <code>New</code> and <code>new</code> both are considered to be same. But on linux the case is sensitive.</p>
<p>Configuration of Linux:</p>
<p>MySQL 5.5.33, phpMyAdmin: 4.0.5, PHP: 5.2.17</p>
<p>Configuration of Windows: </p>
<p>MySql: 5.6.11, phpMyAdmin: 4.0.4.1, PHP: 5.5.0</p>
<p>Is there any way to make them common for both systems? Or any alternative approach?</p> | 23,153,922 | 3 | 0 | null | 2014-04-18 12:09:31.203 UTC | 5 | 2020-02-25 06:45:07.86 UTC | 2020-02-25 06:45:07.86 UTC | null | 5,411,817 | null | 2,952,562 | null | 1 | 14 | mysql|linux|windows | 58,562 | <p>The <strong><code>DEFAULT CURRENT_TIMESTAMP</code></strong> support for a <strong><code>DATETIME</code></strong> (datatype) was added in MySQL 5.6.</p>
<p>In 5.5 and earlier versions, this applied only to <strong><code>TIMESTAMP</code></strong> (datatype) columns.</p>
<p>It is possible to use a <strong><code>BEFORE INSERT</code></strong> trigger in 5.5 to assign a default value to a column.</p>
<pre><code> DELIMITER $$
CREATE TRIGGER ...
BEFORE INSERT ON mytable
FOR EACH ROW
BEGIN
IF NEW.mycol IS NULL THEN
SET NEW.mycol = NOW();
END IF;
END$$
</code></pre>
<hr>
<p><strike>
Case sensitivity (of queries against values stored in columns) is due to the <strong><code>collation</code></strong> used for the column. Collations ending in <strong><code>_ci</code></strong> are case insensitive. For example <strong><code>latin1_swedish_ci</code></strong> is case insensitive, but <strong><code>latin1_general_cs</code></strong> is case sensitive.</p>
<p>The output from <strong><code>SHOW CREATE TABLE foo</code></strong> will show the character set and collation for the character type columns. This is specified at a per-column level. The "default" specified at the table level applies to new columns added to the table when the new column definition doesn't specify a characterset.</p>
<h2></strike></h2>
<p><strong>UPDATE</strong></p>
<p>Kaii pointed out that my answer regarding "case sensitivity" deals with values stored within columns, and whether queries will return a value from a column containing a value of <code>"New"</code> will be returned with a predicate like <code>"t.col = 'new'"</code>.</p>
<p>See Kaii's answer regarding <strong>identifiers</strong> (e.g. table names) being handled differently (by default) on Windows than on Linux.</p> |
19,820,020 | hg remove all files listed in .hgignore | <p>I have a mercurial repo with <code>.hgignore</code> file. I want to remove all files from disk (<code>hg remove</code>) in this repo which match pattern(s) listed in <code>.hgignore</code>.</p>
<p>I can list all ignored files with <code>hg status -i</code> but I don't know how can I delete them.</p>
<p>.hgignore contents:</p>
<pre><code>syntax: glob
build
\.egg*
*.pyc
.DS_Store
*.sublime-*
</code></pre> | 19,826,709 | 2 | 0 | null | 2013-11-06 18:35:28.55 UTC | 8 | 2018-02-22 10:27:37.897 UTC | null | null | null | null | 355,507 | null | 1 | 18 | mercurial|ubuntu-13.10 | 5,262 | <p>You can only run <code>hg remove</code> on files that are tracked. To remove tracked files that match the <code>.hgignore</code> patterns, run this command</p>
<pre><code>$ hg forget "set:hgignore() and not ignored()"
</code></pre>
<p>This uses a <a href="http://www.selenic.com/mercurial/hg.1.html#fileset" rel="noreferrer">fileset</a> to select the right files.</p>
<p>If you want to remove files that are already ignored by Mercurial (not tracked), then see the <a href="https://www.mercurial-scm.org/wiki/PurgeExtension" rel="noreferrer">purge extension</a>. That can be used to cleanup a working copy so that it looks like a fresh checkout.</p> |
34,071,879 | How do I use, or set up sonar-project.properties file? | <p>I have very little exposure to SonarQube but have been asked to make a document explaining how to set up / use "sonar-project.properties file". Any information or input would be greatly appreciated.</p> | 34,083,626 | 2 | 0 | null | 2015-12-03 16:59:35.977 UTC | 6 | 2022-07-18 14:25:29.963 UTC | 2020-12-18 11:09:03.967 UTC | null | 1,783,163 | null | 5,422,190 | null | 1 | 40 | sonarqube|properties-file|sonar-runner | 110,307 | <p>Here are some resources to get you started</p>
<p><a href="https://www.wrightfully.com/setting-up-sonar-analysis-for-c-projects/" rel="noreferrer">https://www.wrightfully.com/setting-up-sonar-analysis-for-c-projects/</a> - See Step 6: The sonar-project.properties file.</p>
<p><a href="https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner" rel="noreferrer">https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner</a></p>
<p>There are also some sample projects on github, you can refer to the project.properties files there as well,
<a href="https://github.com/SonarSource/sonar-scanning-examples" rel="noreferrer">https://github.com/SonarSource/sonar-scanning-examples</a></p> |
17,974,255 | Is there a way to see which email address a contact form is sending it content to | <p>Is there any way to see which email address a contact form is sending it content to ? </p>
<p>Someone asked me this today, and i thought the answer would be no, but it got me thinking is there a way..</p>
<p>The only thing i could think of looking at would be the POST data which would show you were the data was posted to and which content was sent, but not the actual server side script which would probably hold the recipients address.. so using that approach i couldn't see how you could, but i wandered if there was another way.. any ideas ?</p> | 17,974,784 | 1 | 0 | null | 2013-07-31 15:14:25.783 UTC | 2 | 2018-10-13 02:26:25.767 UTC | null | null | null | null | 1,183,150 | null | 1 | 9 | email|reverse-engineering|contact-form|email-address | 70,765 | <p>There are some ocasions when the contact form will send a destination address in a hidden HTML field, but I would say that those are the minority of all contact pages I have seen.</p>
<p>There is no need to pass the recipient of the email address if you only really process it internally.</p>
<p>Actually, the contact form might not even generate an email from your submission, sometime it will just store it in a database and use some other form of notification and access to your submission.</p>
<p>I would check the contact form page source (crtl-u on many browsers) and search for the "@" sign. If you find none, it is probably because they just keep on server, or no email is sent at all.</p> |
35,415,101 | Prevent Android logcat clear during app restart | <p>I am using Android Studio 1.5.1 and it clears the logcat buffer during app restart. Now my app crashes, restarts and I don't see what happens just before the crash.</p>
<p>Is there a way for logcat in Android Studio not to clear during the app restart? I wanted to increase the logcat buffer size, but could not find the option it in the current version of AS. </p> | 36,784,131 | 2 | 0 | null | 2016-02-15 17:08:10.057 UTC | 8 | 2021-05-13 15:49:24.157 UTC | 2016-08-03 14:18:50.05 UTC | null | 2,065,587 | null | 96,410 | null | 1 | 70 | android-studio|logcat|android-logcat | 12,793 | <p>I had the same issue, but looks more like a feature than a bug:</p>
<p>In AndroidStudio, the default setting for the Logcat window seems to be "Show only selected Application" (top right corner of the Logcat window)... which is looking at the log of the selected process (your current launch by default). So when your app crashes during testing, that process is gone, so the filter clears the log.</p>
<p>Instead, select "Edit Filter Configuration..." and set up a filter for your app, eg:</p>
<ul>
<li>FilterName: MyApp</li>
<li>PackageName: com.example.myapp (<< replace with your app's package name)</li>
</ul>
<p>...and then select that filter for future runs. This should keep the log there for you, even after the app crashes.</p>
<p><a href="https://stackoverflow.com/a/31040015/6058777">duplicate</a></p> |
47,070,997 | How to get "key" prop from React element (on change)? | <p>I want to get option's value and key when select <code>onChange</code>.</p>
<p>I know I can get option's <em>value</em> simplicity used <code>event.target.value</code> in <code>onChangeOption</code> function, but how can I get <code>key</code>?</p>
<pre><code><select onChange={this.onChangeOption} value={country}>
{countryOptions.map((item, key) =>
<option key={key} value={item.value}>
{item.name}
</option>
)}
</select>
</code></pre> | 47,071,992 | 7 | 1 | null | 2017-11-02 08:48:28.357 UTC | 4 | 2022-08-03 03:36:04.347 UTC | 2019-06-06 12:42:08.643 UTC | null | 104,380 | null | 8,180,718 | null | 1 | 64 | javascript|reactjs | 137,488 | <p>Passing key as a prop works obviously, but much quicker way could be to include the key as a custom attribute in your html.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class App extends React.Component {
constructor(props) {
super(props);
this.onSelect = this.onSelect.bind(this);
}
onSelect(event) {
const selectedIndex = event.target.options.selectedIndex;
console.log(event.target.options[selectedIndex].getAttribute('data-key'));
}
render() {
return (
<div>
<select onChange = {this.onSelect}>
<option key="1" data-key="1">One</option>
<option key="2" data-key="2">Two</option> </select>
</div>
);
}
}
ReactDOM.render( < App / > , document.getElementById('root'));</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div></code></pre>
</div>
</div>
</p> |
27,117,337 | Exclude route from express middleware | <p>I have a node app sitting like a firewall/dispatcher in front of other micro services and it uses a middleware chain like below:</p>
<pre><code>...
app.use app_lookup
app.use timestamp_validator
app.use request_body
app.use checksum_validator
app.use rateLimiter
app.use whitelist
app.use proxy
...
</code></pre>
<p>However for a particular GET route I want to skip all of them except rateLimiter and proxy. Is their a way to set a filter like a Rails before_filter using :except/:only?</p> | 27,118,077 | 8 | 1 | null | 2014-11-25 01:30:11.15 UTC | 14 | 2020-05-09 11:20:38.12 UTC | null | null | null | null | 627,408 | null | 1 | 46 | javascript|node.js|express|coffeescript|middleware | 61,042 | <p>Even though there is no build-in middleware filter system in expressjs, you can achieve this in at least two ways.</p>
<p>First method is to mount all middlewares that you want to skip to a regular expression path than includes a negative lookup:</p>
<pre><code>// Skip all middleware except rateLimiter and proxy when route is /example_route
app.use(/\/((?!example_route).)*/, app_lookup);
app.use(/\/((?!example_route).)*/, timestamp_validator);
app.use(/\/((?!example_route).)*/, request_body);
app.use(/\/((?!example_route).)*/, checksum_validator);
app.use(rateLimiter);
app.use(/\/((?!example_route).)*/, whitelist);
app.use(proxy);
</code></pre>
<p>Second method, probably more readable and cleaner one, is to wrap your middleware with a small helper function:</p>
<pre><code>var unless = function(path, middleware) {
return function(req, res, next) {
if (path === req.path) {
return next();
} else {
return middleware(req, res, next);
}
};
};
app.use(unless('/example_route', app_lookup));
app.use(unless('/example_route', timestamp_validator));
app.use(unless('/example_route', request_body));
app.use(unless('/example_route', checksum_validator));
app.use(rateLimiter);
app.use(unless('/example_route', whitelist));
app.use(proxy);
</code></pre>
<p>If you need more powerfull route matching than simple <code>path === req.path</code> you can use <a href="https://github.com/component/path-to-regexp" rel="noreferrer">path-to-regexp module</a> that is used internally by Express.</p>
<p>UPDATE :- In <code>express 4.17</code> <code>req.path</code> returns only '/', so use <code>req.baseUrl</code> :</p>
<pre><code>var unless = function(path, middleware) {
return function(req, res, next) {
if (path === req.baseUrl) {
return next();
} else {
return middleware(req, res, next);
}
};
};
</code></pre> |
43,484,302 | What does ...rest mean in React JSX? | <p>Looking at this React Router Dom v4 example <a href="https://reacttraining.com/react-router/web/example/auth-workflow" rel="noreferrer">https://reacttraining.com/react-router/web/example/auth-workflow</a> I see that <strong>PrivateRoute</strong> component destructures a rest prop like this</p>
<pre><code>const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
fakeAuth.isAuthenticated ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
)
</code></pre>
<p>I want to be certain that <code>{ component: Component, ...rest }</code> means:</p>
<blockquote>
<p>From <code>props</code>, get the Component prop and then all other props are given to you, and rename <code>props</code> to <code>rest</code> so you can avoid naming issues with the props passed to the Route <code>render</code> function</p>
</blockquote>
<p>Am I right?</p> | 43,484,565 | 3 | 1 | null | 2017-04-19 00:29:48.277 UTC | 67 | 2022-01-08 07:15:59.64 UTC | 2022-01-08 07:15:59.64 UTC | null | 10,262,805 | null | 820,067 | null | 1 | 121 | javascript|reactjs|react-router | 88,360 | <p>Sorry, I realized my first answer (while hopefully still providing useful/additional context) doesn't answer your question. Let me try again.</p>
<p>You ask:</p>
<blockquote>
<p>I want to be certain that <code>{ component: Component, ...rest }</code> means:</p>
<p>From <code>props</code>, get the <code>Component</code> prop and then all other <code>props</code> given to
you, and rename <code>props</code> to <code>rest</code> so you can avoid naming issues with the
<code>props</code> passed to the Route <code>render</code> function</p>
</blockquote>
<p>Your interpretation is not quite correct. Based on your thoughts though, it sounds like you're at least aware of the fact that what is happening here amounts to some sort of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring" rel="noreferrer">object destructuring</a> (see second answer and comments there for more clarification).</p>
<p>To give an accurate explanation, let's break down the <code>{ component: Component, ...rest }</code> expression into two separate operations:</p>
<ol>
<li><strong>Operation 1:</strong> Find the <code>component</code> property defined on <code>props</code> (<em>Note</em>: lowercase <strong>c</strong>omponent) and assign it to a new location in state we call <code>Component</code> (<em>Note</em>: capital <strong>C</strong>omponent).</li>
<li><strong>Operation 2:</strong> Then, take all <em>remaining</em> properties defined on the <code>props</code> object and collect them inside an argument called <code>rest</code>.</li>
</ol>
<p>The important point is that you're NOT renaming <code>props</code> to <code>rest</code>. (And nor does it have to do with trying to "avoid naming issues with the <code>props</code> passed to the Route <code>render</code> function".)</p>
<pre class="lang-js prettyprint-override"><code>rest === props;
// => false
</code></pre>
<p>You're simply pulling off <em>the rest</em> (hence why the argument is named that) of the properties defined on your <code>props</code> object into a new argument called <code>rest</code>.</p>
<hr />
<h3>Example Usage</h3>
Here's an example. Let's assume we have an object `myObj` defined as follows:
<pre class="lang-js prettyprint-override"><code>const myObj = {
name: 'John Doe',
age: 35,
sex: 'M',
dob: new Date(1990, 1, 1)
};
</code></pre>
<p>For this example, it may help to just think of <code>props</code> as having the same structure (<em>i.e.</em>, properties and values) as shown in <code>myObj</code>. Now, let's write the following assignment.</p>
<pre class="lang-js prettyprint-override"><code>const { name: Username, ...rest } = myObj
</code></pre>
<p>The statement above amounts to both the <strong>declaration</strong> and <strong>assignment</strong> of two variables (or, I guess, constants). The statement can be thought out as:</p>
<blockquote>
<p>Take property <code>name</code> defined on <code>myObj</code> and assign its value to a new
variable we call <code>Username</code>. Then, take whatever other properties were
defined on <code>myObj</code> (<em>i.e.</em>, <code>age</code>, <code>sex</code> and <code>dob</code>) and collect them
into a new object assigned to the variable we name <code>rest</code>.</p>
</blockquote>
<p>Logging <code>Username</code> and <code>rest</code> to the <code>console</code> would confirm this. We have the following:</p>
<pre class="lang-js prettyprint-override"><code>console.log(Username);
// => John Doe
</code></pre>
<pre class="lang-js prettyprint-override"><code>console.log(rest);
// => { age: 35, sex: 'M', dob: Mon Jan 01 1990 00:00:00 GMT-0800 (PST) }
</code></pre>
<hr />
<h3>Side Note</h3>
You may wonder:
<blockquote>
<p>Why go through the trouble of pulling off the <code>component</code> property
only to rename it <code>Component</code> with a capital letter "C"?</p>
</blockquote>
<p>Yeah, it seems pretty trivial. And, while it is a standard React practice, there's a reason all of <a href="https://facebook.github.io/react/docs/hello-world.html" rel="noreferrer">Facebook's documentation</a> on its framework is written as such. Namely, capitalizing custom components rendered with JSX is less a practice per se than it is a necessity. React, or more properly, <a href="https://stackoverflow.com/questions/33259112/why-do-components-in-react-need-to-be-capitalized">JSX is case-sensitive</a>. Custom components inserted without a capitalized first letter are not rendered to the DOM. This is just how React has defined itself to identify custom components. Thus, had the example not additionally renamed the <code>component</code> property that was pulled off of <code>props</code> to <code>Component</code>, the <code><component {...props} /></code> expression would fail to render properly.</p> |
6,603,362 | Ruby on Rails Switch | <p>Can someone provide an example on how to use switch case in Ruby for variable?</p> | 6,603,562 | 1 | 0 | null | 2011-07-06 21:39:48.23 UTC | 5 | 2013-08-06 19:52:04.297 UTC | 2013-08-06 19:52:04.297 UTC | null | 1,017,941 | null | 806,550 | null | 1 | 66 | ruby|switch-statement | 101,226 | <p>I assume you refer to case/when.</p>
<pre><code>case a_variable # a_variable is the variable we want to compare
when 1 #compare to 1
puts "it was 1"
when 2 #compare to 2
puts "it was 2"
else
puts "it was something else"
end
</code></pre>
<p>or</p>
<pre><code>puts case a_variable
when 1
"it was 1"
when 2
"it was 2"
else
"it was something else"
end
</code></pre>
<p>EDIT</p>
<p>Something that maybe not everyone knows about but what can be very useful is that you can use regexps in a case statement.</p>
<pre><code>foo = "1Aheppsdf"
what = case foo
when /^[0-9]/
"Begins with a number"
when /^[a-zA-Z]/
"Begins with a letter"
else
"Begins with something else"
end
puts "String: #{what}"
</code></pre> |
56,410,074 | How to set the background color of a Row() in Flutter? | <p>I'm trying to set up a background color for a Row() widget, but Row itself has no background color or color attribute. I've been able to set the background color of a container to grey, right before the purple-backgrounded text, but the text itself does not fill the background completely and the following spacer does not take any color at all.</p>
<p>So how can I have the Row background set to the "HexColor(COLOR_LIGHT_GREY)" value so it spans over the whole row? </p>
<p>Any idea? Thanks a lot!</p>
<p><a href="https://i.stack.imgur.com/hCeM3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hCeM3.png" alt="enter image description here"></a></p>
<p>Here's the code that I have so far:</p>
<pre><code>import 'package:flutter/material.dart';
import '../manager/ShoppingListManager.dart';
import '../model/ShoppingListModel.dart';
import '../hexColor.dart';
import '../Constants.dart';
class ShoppingListWidget extends StatelessWidget {
final Color color = Colors.amberAccent;
final int shoppingListIndex;
ShoppingListWidget({this.shoppingListIndex});
@override
Widget build(BuildContext context) {
ShoppingListManager slm = new ShoppingListManager();
String shoppingListName =
slm.myShoppingLists.shoppingLists[shoppingListIndex].name;
int categoryCount =
slm.myShoppingLists.shoppingLists[shoppingListIndex].categories.length;
return Scaffold(
appBar: AppBar(
title: Text(shoppingListName),
automaticallyImplyLeading: true,
),
body: ListView.builder(
itemBuilder: (context, index) {
Category cat = slm.myShoppingLists.shoppingLists[shoppingListIndex]
.categories[index];
return Container(
decoration: new BoxDecoration(
border: new Border.all(color: Colors.grey[500]),
color: Colors.white,
),
child: new Column(
children: <Widget>[
getCategoryWidget(context, cat),
getCategoryItems(context, cat),
],
),
);
},
itemCount: categoryCount,
),
);
}
// Render the category "headline" row where I want to set the background color
// to HexColor(COLOR_LIGHT_GREY)
Widget getCategoryWidget(BuildContext context, Category cat) {
return new Row(
children: <Widget>[
new Container(height: 40.0, width: 10.0, color: HexColor(cat.color)),
new Container(
height: 40.0, width: 15.0, color: HexColor(COLOR_LIGHT_GREY)),
new Container(
child: new Text("Category", textAlign: TextAlign.start,
style: TextStyle(
fontFamily: 'Bold',
fontSize: 18.0,
color: Colors.black),
),
decoration: new BoxDecoration(
color: Colors.purple,
),
height: 40.0,
),
Spacer(),
CircleAvatar(
backgroundImage:
new AssetImage('assets/icons/food/food_settings.png'),
backgroundColor: HexColor(COLOR_LIGHT_GREY),
radius: 15.0,
),
new Container(height: 15.0, width: 10.0, color: Colors.transparent),
],
);
}
// render the category items
Widget getCategoryItems(BuildContext context, Category cat) {
return ListView.builder(
itemBuilder: (context, index) {
String itemName = "Subcategory";
return new Row(children: <Widget>[
new Container(height: 40.0, width: 5.0, color: HexColor(cat.color)),
new Container(height: 40.0, width: 20.0, color: Colors.white),
new Container(
child: new Text(itemName),
color: Colors.white,
),
Spacer()
]);
},
itemCount: cat.items.length,
shrinkWrap: true,
physics:
ClampingScrollPhysics(),
);
}
}
</code></pre> | 56,410,215 | 5 | 1 | null | 2019-06-01 20:07:53.93 UTC | 5 | 2022-03-22 15:11:21.54 UTC | 2022-01-04 20:17:59.79 UTC | null | 6,618,622 | null | 1,214,761 | null | 1 | 65 | flutter|dart|flutter-layout | 93,787 | <p>Just wrap your Row with a Container with colour property like below: </p>
<pre><code> Container(
color: Colors.black,
child: Row(
children: <Widget>[
Expanded(
child: Text('Demo', style: TextStyle(color: Colors.white),),
)
],
),
)
</code></pre> |
24,186,648 | Swift equivalent for MIN and MAX macros | <p>In C / Objective-C it is possible to find the minimum and maximum value between two numbers using MIN and MAX macros. Swift doesn't support macros and it seems that there are no equivalents in the language / base library. Should one go with a custom solution, maybe based on generics like this <a href="http://www.cplusplus.com/reference/algorithm/max/" rel="noreferrer">one</a>?</p> | 24,186,709 | 5 | 0 | null | 2014-06-12 14:13:34.403 UTC | 13 | 2021-09-23 16:40:09.237 UTC | null | null | null | null | 3,734,205 | null | 1 | 102 | generics|swift | 60,280 | <p><code>min</code> and <code>max</code> are defined in Swift:</p>
<pre><code>func max<T : Comparable>(x: T, y: T, rest: T...) -> T
func min<T : Comparable>(x: T, y: T, rest: T...) -> T
</code></pre>
<p>and used like so:</p>
<pre><code>let min = min(1, 2)
let max = max(1, 2)
</code></pre>
<p>See this great writeup on <a href="https://github.com/chenee/swift-74-functions" rel="noreferrer">documented & undocumented built-in functions in Swift</a>.</p> |
5,891,431 | 416 Requested Range Not Satisfiable | <p>Context: I am using a software package called Social Engine. It is extremely buggy. </p>
<p>Anyway, I asked (paid even) the Social Engine people to do an upgrade and when they finally did so, I logged into the site and noticed that the styles were all missing. I opened a support ticket and all they told me was that it was a 416 error and to contact my ISP.</p>
<p>This error was found by testing the direct link to the CSS files which are located in a writable folder in the software.</p>
<p><a href="http://ministersdev3.themonastery.org/application/css.php?request=application/themes/monastery-theme/theme.css&c=6" rel="noreferrer">http://ministersdev3.themonastery.org/application/css.php?request=application/themes/monastery-theme/theme.css&c=6</a></p>
<p>I started doing my research only to find it's an extremely rare error and I couldn't see any suggestions for turning range requesting off on my Ubuntu 10.10 Linode server (running latest Apache and PHP5 with APC extension installed). Perhaps it's a software issue? Someway the caching with APC is working? I reset the caching in this software to 60 seconds and made sure it was using APC. Still no dice. </p>
<p>Is it something their software may be doing that I would need to look into patching?</p> | 5,898,834 | 3 | 1 | null | 2011-05-05 00:38:12.953 UTC | 2 | 2014-05-09 03:44:20.573 UTC | 2011-05-07 10:35:53.19 UTC | null | 283,078 | null | 418,046 | null | 1 | 23 | apache|http|http-headers|ubuntu-10.10 | 47,242 | <p>The issue could be due to your browser having cached the original CSS files and trying to request byte ranges of the new files. See for example <a href="http://code.google.com/p/chromium/issues/detail?id=68298" rel="noreferrer">this bug with Chrome</a>.</p>
<p>As far as disabling range requesting, it might not be necessary if you clear your browser cache, but if you need it you could try the following Apache config:</p>
<pre><code>Header unset Accept-Ranges
</code></pre>
<p>This will tell clients that they cannot use the <code>Range</code> request header to request byte ranges of your files.</p> |
6,006,494 | git submodule modified files status | <p>I've added a submodule in my main git folder tree and haven't changed anything but it's showing up modified. What do I do about this?</p>
<pre><code>$ git status
# On branch master
# Changed but not updated:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: example.com/soundmanager
#
no changes added to commit (use "git add" and/or "git commit -a")
</code></pre>
<p>I've tried a git submodule update, but it doesn't do anything.</p> | 6,006,919 | 3 | 1 | null | 2011-05-15 04:30:17.85 UTC | 20 | 2019-11-26 22:27:30.893 UTC | 2014-03-20 05:12:07.073 UTC | null | 272,287 | null | 332,913 | null | 1 | 52 | git|git-submodules | 30,996 | <p>The way that the status of git submodules is reported has changed a lot over recent versions of git, so you should really include the output of <code>git --version</code> as well for us to be able to help accurately.</p>
<p>However, in any case, the output of <code>git diff example.com/soundmanager</code> should tell you more. If you see output with the same commit name, but with <code>-dirty</code> added to the new version, e.g.:</p>
<pre><code>diff --git a/example.com/soundmanager b/example.com/soundmanager
--- a/example.com/soundmanager
+++ b/example.com/soundmanager
@@ -1 +1 @@
-Subproject commit c5c6bbaf616d64fbd873df7b7feecebb81b5aee7
+Subproject commit c5c6bbaf616d64fbd873df7b7feecebb81b5aee7-dirty
</code></pre>
<p>... than that means that <code>git status</code> in the submodule isn't clean - try <code>cd example.com/soundmanager</code> and then <code>git status</code> to see what's going on.</p>
<p>On the other hand, if you see different commit versions, e.g.:</p>
<pre><code>diff --git a/example.com/soundmanager b/example.com/soundmanager
index c4478af..c79d9c8 160000
--- a/example.com/soundmanager
+++ b/example.com/soundmanager
@@ -1 +1 @@
-Subproject commit c4478af032e604bed605e82d04a248d75fa513f7
+Subproject commit c79d9c83c2864665ca3fd0b11e20a53716d0cbb0
</code></pre>
<p>... that means that the version that your submodule is at (i.e. what you see from <code>cd example.com/soundmanager && git show HEAD</code>) is different from the version committed in the main project's tree (i.e. what you see from <code>git rev-parse HEAD:example.com/soundmanager</code>). If the former is right, you should add and commit the new version of the submodule in your main project, with something like:</p>
<pre><code>git add example.com/soundmanager
git commit -m "Update the soundmanager submodule"
</code></pre>
<p>On the other hand, if the latter is what you want, you can change the version that the submodule is at with:</p>
<pre><code>git submodule update example.com/soundmanager
</code></pre> |
6,033,905 | Create the perfect JPA entity | <p>I've been working with JPA (implementation Hibernate) for some time now and each time I need to create entities I find myself struggling with issues as AccessType, immutable properties, equals/hashCode, ... .<br>
So I decided to try and find out the general best practice for each issue and write this down for personal use.<br>
I would not mind however for anyone to comment on it or to tell me where I'm wrong.</p>
<h2>Entity Class</h2>
<ul>
<li><p>implement Serializable </p>
<p>Reason: <em>The specification says you have to, but some JPA providers do not enforce this. Hibernate as JPA provider does not enforce this, but it can fail somewhere deep in its stomach with ClassCastException, if Serializable has not been implemented.</em></p></li>
</ul>
<h2>Constructors</h2>
<ul>
<li><p>create a constructor with all required fields of the entity </p>
<p><em>Reason: A constructor should always leave the instance created in a sane state.</em> </p></li>
<li><p>besides this constructor: have a package private default constructor </p>
<p><em>Reason: Default constructor is required to have Hibernate initialize the entity; private is allowed but package private (or public) visibility is required for runtime proxy generation and efficient data retrieval without bytecode instrumentation.</em></p></li>
</ul>
<h2>Fields/Properties</h2>
<ul>
<li><p>Use field access in general and property access when needed </p>
<p><em>Reason: this is probably the most debatable issue since there are no clear and convincing arguments for one or the other (property access vs field access); however, field access seems to be general favourite because of clearer code, better encapsulation and no need to create setters for immutable fields</em> </p></li>
<li><p>Omit setters for immutable fields (not required for access type field)</p></li>
<li>properties may be private<br>
Reason: I once heard that protected is better for (Hibernate) performance but all I can find on the web is: <em>Hibernate can access public, private, and protected accessor methods, as well as public, private and protected fields directly. The choice is up to you and you can match it to fit your application design.</em></li>
</ul>
<h2>Equals/hashCode</h2>
<ul>
<li>Never use a generated id if this id is only set when persisting the entity</li>
<li>By preference: use immutable values to form a unique Business Key and use this to test equality</li>
<li>if a unique Business Key is not available use a non-transient <strong>UUID</strong> which is created when the entity is initialised; See <a href="https://web.archive.org/web/20171211235806/http://www.onjava.com/pub/a/onjava/2006/09/13/dont-let-hibernate-steal-your-identity.html" rel="noreferrer">this great article</a> for more information.</li>
<li><strong>never</strong> refer to related entities (ManyToOne); if this entity (like a parent entity) needs to be part of the Business Key then compare the ID's only. Calling getId() on a proxy will not trigger the loading of the entity, as long as you're using <a href="https://stackoverflow.com/questions/3736818/hibernate-generating-sql-queries-when-accessing-associated-entitys-id/3739197#3739197">property access type</a>.</li>
</ul>
<h2>Example Entity</h2>
<pre><code>@Entity
@Table(name = "ROOM")
public class Room implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name = "room_id")
private Integer id;
@Column(name = "number")
private String number; //immutable
@Column(name = "capacity")
private Integer capacity;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "building_id")
private Building building; //immutable
Room() {
// default constructor
}
public Room(Building building, String number) {
// constructor with required field
notNull(building, "Method called with null parameter (application)");
notNull(number, "Method called with null parameter (name)");
this.building = building;
this.number = number;
}
@Override
public boolean equals(final Object otherObj) {
if ((otherObj == null) || !(otherObj instanceof Room)) {
return false;
}
// a room can be uniquely identified by it's number and the building it belongs to; normally I would use a UUID in any case but this is just to illustrate the usage of getId()
final Room other = (Room) otherObj;
return new EqualsBuilder().append(getNumber(), other.getNumber())
.append(getBuilding().getId(), other.getBuilding().getId())
.isEquals();
//this assumes that Building.id is annotated with @Access(value = AccessType.PROPERTY)
}
public Building getBuilding() {
return building;
}
public Integer getId() {
return id;
}
public String getNumber() {
return number;
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(getNumber()).append(getBuilding().getId()).toHashCode();
}
public void setCapacity(Integer capacity) {
this.capacity = capacity;
}
//no setters for number, building nor id
}
</code></pre>
<p>Other suggestions to add to this list are more than welcome...</p>
<p><strong>UPDATE</strong></p>
<p>Since reading <a href="https://web.archive.org/web/20171211235806/http://www.onjava.com/pub/a/onjava/2006/09/13/dont-let-hibernate-steal-your-identity.html" rel="noreferrer">this article</a> I have adapted my way of implementing eq/hC:</p>
<ul>
<li>if an immutable simple business key is available: use that</li>
<li>in all other cases: use a uuid</li>
</ul> | 14,822,709 | 4 | 5 | null | 2011-05-17 16:16:00.277 UTC | 408 | 2022-09-07 00:29:59.457 UTC | 2018-10-03 11:54:08.817 UTC | null | 3,988,992 | null | 190,596 | null | 1 | 445 | java|hibernate|jpa|equals | 179,381 | <p>I'll try to answer several key points: this is from long Hibernate/ persistence experience including several major applications.</p>
<p><strong>Entity Class: implement Serializable?</strong></p>
<p><em>Keys</em> needs to implement Serializable. Stuff that's going to go in the HttpSession, or be sent over the wire by RPC/Java EE, needs to implement Serializable. Other stuff: not so much. Spend your time on what's important.</p>
<p><strong>Constructors: create a constructor with all required fields of the entity?</strong></p>
<p>Constructor(s) for application logic, should have only a few critical "foreign key" or "type/kind" fields which will always be known when creating the entity. The rest should be set by calling the setter methods -- that's what they're for.</p>
<p>Avoid putting too many fields into constructors. Constructors should be convenient, and give basic sanity to the object. Name, Type and/or Parents are all typically useful.</p>
<p>OTOH if application rules (today) require a Customer to have an Address, leave that to a setter. That is an example of a "weak rule". Maybe next week, you want to create a Customer object before going to the Enter Details screen? Don't trip yourself up, leave possibility for unknown, incomplete or "partially entered" data.</p>
<p><strong>Constructors: also, package private default constructor?</strong></p>
<p>Yes, but use 'protected' rather than package private. Subclassing stuff is a real pain when the necessary internals are not visible.</p>
<p><strong>Fields/Properties</strong></p>
<p>Use 'property' field access for Hibernate, and from outside the instance. Within the instance, use the fields directly. Reason: allows standard reflection, the simplest & most basic method for Hibernate, to work.</p>
<p>As for fields 'immutable' to the application -- Hibernate still needs to be able to load these. You could try making these methods 'private', and/or put an annotation on them, to prevent application code making unwanted access.</p>
<p>Note: when writing an equals() function, use getters for values on the 'other' instance! Otherwise, you'll hit uninitialized/ empty fields on proxy instances.</p>
<p><strong>Protected is better for (Hibernate) performance?</strong></p>
<p>Unlikely.</p>
<p><strong>Equals/HashCode?</strong></p>
<p>This is relevant to working with entities, before they've been saved -- which is a thorny issue. Hashing/comparing on immutable values? In most business applications, there aren't any.</p>
<p>A customer can change address, change the name of their business, etc etc -- not common, but it happens. Corrections also need to be possible to make, when the data was not entered correctly.</p>
<p>The few things that are normally kept immutable, are Parenting and perhaps Type/Kind -- normally the user recreates the record, rather than changing these. But these do not uniquely identify the entity!</p>
<p>So, long and short, the claimed "immutable" data isn't really. Primary Key/ ID fields are generated for the precise purpose, of providing such guaranteed stability & immutability.</p>
<p>You need to plan & consider your need for comparison & hashing & request-processing work phases when A) working with "changed/ bound data" from the UI if you compare/hash on "infrequently changed fields", or B) working with "unsaved data", if you compare/hash on ID.</p>
<p><strong>Equals/HashCode -- if a unique Business Key is not available, use a non-transient UUID which is created when the entity is initialized</strong></p>
<p>Yes, this is a good strategy when required. Be aware that UUIDs are not free, performance-wise though -- and clustering complicates things.</p>
<p><strong>Equals/HashCode -- never refer to related entities</strong></p>
<p>"If related entity (like a parent entity) needs to be part of the Business Key then add a non insertable, non updatable field to store the parent id (with the same name as the ManytoOne JoinColumn) and use this id in the equality check"</p>
<p>Sounds like good advice.</p>
<p>Hope this helps!</p> |
2,168,704 | WCF Dependency injection and abstract factory | <p>I have this wcf method</p>
<pre><code>Profile GetProfileInfo(string profileType, string profileName)
</code></pre>
<p>and a business rule:</p>
<p>if profileType is "A" read from database.</p>
<p>if profileType is "B" read from xml file.</p>
<p>The question is: how to implement it using a dependency injection container?</p> | 2,168,882 | 2 | 0 | null | 2010-01-30 17:26:38.517 UTC | 12 | 2016-04-12 05:26:19.003 UTC | 2014-09-22 14:33:32.267 UTC | null | 1,911,306 | null | 43,162 | null | 1 | 19 | wcf|dependency-injection|factory-pattern | 8,922 | <p>Let's first assume that you have an IProfileRepository something like this:</p>
<pre><code>public interface IProfileRepository
{
Profile GetProfile(string profileName);
}
</code></pre>
<p>as well as two implementations: <code>DatabaseProfileRepository</code> and <code>XmlProfileRepository</code>. The issue is that you would like to pick the correct one based on the value of profileType.</p>
<p>You can do this by introducing this <strong>Abstract Factory</strong>:</p>
<pre><code>public interface IProfileRepositoryFactory
{
IProfileRepository Create(string profileType);
}
</code></pre>
<p>Assuming that the IProfileRepositoryFactory has been injected into the service implementation, you can now implement the GetProfileInfo method like this:</p>
<pre><code>public Profile GetProfileInfo(string profileType, string profileName)
{
return this.factory.Create(profileType).GetProfile(profileName);
}
</code></pre>
<p>A concrete implementation of IProfileRepositoryFactory might look like this:</p>
<pre><code>public class ProfileRepositoryFactory : IProfileRepositoryFactory
{
private readonly IProfileRepository aRepository;
private readonly IProfileRepository bRepository;
public ProfileRepositoryFactory(IProfileRepository aRepository,
IProfileRepository bRepository)
{
if(aRepository == null)
{
throw new ArgumentNullException("aRepository");
}
if(bRepository == null)
{
throw new ArgumentNullException("bRepository");
}
this.aRepository = aRepository;
this.bRepository = bRepository;
}
public IProfileRepository Create(string profileType)
{
if(profileType == "A")
{
return this.aRepository;
}
if(profileType == "B")
{
return this.bRepository;
}
// and so on...
}
}
</code></pre>
<p>Now you just need to get your DI Container of choice to wire it all up for you...</p> |
1,785,422 | How do you put HTML or XML into a YAML? | <p>I would like to store HTML snippets inside a <a href="http://en.wikipedia.org/wiki/YAML" rel="noreferrer">YAML</a> file. What is the best way to do that?</p>
<p>Something like:</p>
<pre><code>myhtml: |
<div>
<a href="#">whatever</a>
</div>
</code></pre> | 1,786,044 | 2 | 0 | null | 2009-11-23 19:31:06.263 UTC | 4 | 2018-09-06 00:01:56.12 UTC | 2017-12-26 21:29:13.373 UTC | null | 42,223 | null | 217,275 | null | 1 | 31 | yaml|configuration-files|code-snippets|markup | 31,701 | <p><strong>Example</strong></p>
<p>Here is a sample record from a YAML-based snippet management system I created years ago:</p>
<pre><code>- caption: fieldset msie5
tinycap: fieldset
domain: html
desc: fieldset and legend tag
wwbody: |
<fieldset>
<legend>legend</legend>
</fieldset>
</code></pre>
<p>You can repeat that or something like it for all the snippets you want to manage. This particular system stores the snippets as an array of name-value pairs (Perl people would call this an AoH). If you do not need all this extra information, just two name-value pairs will suffice (e.g., caption + body). </p>
<p>The nice thing about this system: YAML indentation prevents "delimiter collision" problems. You never have to use <a href="https://xkcd.com/1638/" rel="noreferrer">clumsy</a> <a href="https://en.wikipedia.org/wiki/Leaning_toothpick_syndrome" rel="noreferrer">escape</a> <a href="https://en.wikipedia.org/wiki/Delimiter#Delimiter_collision" rel="noreferrer">sequences</a> inside your snippet body.</p>
<p><strong>Text Editor or IDE alternative</strong></p>
<p>Note: Increasingly, text editors and IDEs support flexible snippet management options natively, so you may want to consider using the format of a text editor rather than re-inventing your own. If you do re-invent your own, you can write a script to translate your YAML format into the native format of a text editor if you later decide you want to do that.</p>
<p><strong>See also:</strong></p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Snippet_%28programming%29" rel="noreferrer">http://en.wikipedia.org/wiki/Snippet_%28programming%29</a></li>
<li><a href="http://en.wikipedia.org/wiki/Delimiter#Delimiter_collision" rel="noreferrer">http://en.wikipedia.org/wiki/Delimiter#Delimiter_collision</a></li>
<li><a href="http://perldoc.perl.org/perldsc.html#ARRAYS-OF-HASHES" rel="noreferrer">http://perldoc.perl.org/perldsc.html#ARRAYS-OF-HASHES</a> (Perl AoH)</li>
<li><a href="http://www.perlmonks.org/index.pl/?node_id=347905" rel="noreferrer">http://www.perlmonks.org/index.pl/?node_id=347905</a></li>
</ul> |
1,470,777 | Forms Authentication Timeout vs Session Timeout | <p>In my asp.net website i am using asp.net form authentication with following configuration</p>
<pre><code><authentication mode="Forms">
<forms loginUrl="~/Pages/Common/Login.aspx"
defaultUrl="~/Pages/index.aspx"
protection="All"
timeout="30"
name="MyAuthCookie"
path="/"
requireSSL="false"
cookieless="UseDeviceProfile"
enableCrossAppRedirects="false" >
</forms>
</authentication>
</code></pre>
<p>I have following questions</p>
<ol>
<li><p>What should be timeout value for session because i am using sliding expiration inside form authention due to which session will expire before form authentication. How can i protect it?</p></li>
<li><p>After formauthentication log out i would like to redirect page at logout.aspx but it is automatically redirect me at loginpage.aspx. How is it possible?</p></li>
</ol> | 1,470,793 | 2 | 0 | null | 2009-09-24 10:03:04.61 UTC | 44 | 2014-12-22 22:36:37.807 UTC | 2014-12-22 22:36:37.807 UTC | null | 284,598 | null | 133,098 | null | 1 | 65 | asp.net|forms|session|timeout|asp.net-3.5 | 101,168 | <ol>
<li>To be on the safe side: TimeOut(Session) <= TimeOut(FormsAuthentication) * 2</li>
<li>If you want to show page other than specified in loginUrl attribute after authentication timeout you need to handle this manually as ASP.NET does not provide a way of doing it.</li>
</ol>
<p>To achieve #2 you can manually check the cookie and its AuthenticationTicket for expiration and redirect to your custom page if they have expired.<br>
You can do in it in one of the events: <a href="http://msdn.microsoft.com/en-us/library/system.web.httpapplication.acquirerequeststate(VS.71).aspx" rel="noreferrer">AcquireRequestState</a>, <a href="http://msdn.microsoft.com/en-us/library/system.web.httpapplication.authenticaterequest(VS.71).aspx" rel="noreferrer">AuthenticateRequest</a>.</p>
<p>Sample code in the event can look like:</p>
<pre><code>// Retrieve AuthenticationCookie
var cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null) return;
FormsAuthenticationTicket ticket = null;
try {
ticket = FormsAuthentication.Decrypt(cookie.Value);
} catch (Exception decryptError) {
// Handle properly
}
if (ticket == null) return; // Not authorised
if (ticket.Expiration > DateTime.Now) {
Response.Redirect("SessionExpiredPage.aspx"); // Or do other stuff here
}
</code></pre> |
29,461,693 | How can I get cargo to recompile changed files automatically? | <p>I have heard cargo has the ability to automatically recompile changed source files, but I'm having a hard time figuring out how to tell it to do so.</p>
<p>For now, I am manually running <code>cargo build</code> or <code>cargo run</code> every time I want to type check my code. I would prefer to instead simply save the file and see the results in the neighboring terminal window.</p>
<p>In case you still have no idea what I'm talking about, I'm looking for the cargo equivalent of <code>sbt ~compile</code> or <code>sbt ~run</code>.</p>
<p>It seems strangely hard to find, so I'm starting to wonder if it's really supported. It's possible someone had said cargo could detect changed files and recompile them when what he meant to say was that cargo could detect <em>unchanged</em> files and <em>avoid</em> recompiling them, like <code>make</code>.</p> | 38,117,745 | 6 | 0 | null | 2015-04-05 20:09:18.943 UTC | 9 | 2022-03-11 12:40:02.687 UTC | 2015-04-05 20:15:30.417 UTC | null | 155,423 | null | 2,343,847 | null | 1 | 57 | rust|rust-cargo | 15,075 | <h3>cargo watch</h3>
<p>In case you are working on a server project (e.g. hyper, iron, etc) that keeps running and you need it to be restarted when files change, you can use <a href="https://github.com/watchexec/cargo-watch" rel="noreferrer"><code>cargo watch</code></a>. Install:</p>
<pre><code>cargo install cargo-watch
</code></pre>
<p>And then run:</p>
<pre><code>cargo watch -x run
</code></pre>
<p>And to watch changes in only the <code>src</code> folder and clear the console use:</p>
<pre><code>cargo watch -c -w src -x run
</code></pre>
<p>See the <a href="https://github.com/watchexec/cargo-watch#readme" rel="noreferrer">cargo-watch README</a> for more examples.</p>
<h3>watchexec</h3>
<p>Alternatively, you can use <a href="https://github.com/watchexec/watchexec" rel="noreferrer">watchexec</a>. Install it:</p>
<pre><code>cargo install watchexec-cli
</code></pre>
<p>And then use it like this:</p>
<pre><code>watchexec -r cargo run
</code></pre> |
29,124,126 | Polymorphic JSON Deserialization failing using Json.Net | <p>I'm trying to deserialize some JSON to various sub-classes using a custom <code>JsonConverter</code></p>
<p>I followed <a href="https://stackoverflow.com/a/19308474/1351298">this</a> almost to the point.</p>
<p>My abstract base-class:</p>
<pre><code>abstract class MenuItem
{
public String Title { get; set; }
public String Contents { get; set; }
public List<MenuItem> Submenus { get; set; }
public String Source { get; set; }
public String SourceType { get; set; }
public abstract void DisplayContents();
}
</code></pre>
<p>And my derived <code>JsonConverter</code>:</p>
<pre><code>class MenuItemConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(MenuItem).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject item = JObject.Load(reader);
switch (item["SourceType"].Value<String>())
{
case SourceType.File: return item.ToObject<Menu.FileMenu>();
case SourceType.Folder: return item.ToObject<Menu.FolderMenu>();
case SourceType.Json: return item.ToObject<Menu.JsonMenu>();
case SourceType.RestGet: return item.ToObject<Menu.RestMenu>();
case SourceType.Rss: return item.ToObject<Menu.RssMenu>();
case SourceType.Text: return item.ToObject<Menu.TextMenu>();
case SourceType.Url: return item.ToObject<Menu.UrlMenu>();
default: throw new ArgumentException("Invalid source type");
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
</code></pre>
<p><code>SourceType</code> is just a static class holding some string constants.</p>
<p>The JSON file is deserialized like this:</p>
<pre><code>JsonConvert.DeserializeObject<MenuItem>(File.ReadAllText(menuPath), new MenuItemConverter());
</code></pre>
<p>Now, my issue is that whenever I run the code I get the following error:</p>
<pre><code>An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code
Additional information: Could not create an instance of type ConsoleMenu.Model.MenuItem. Type is an interface or abstract class and cannot be instantiated. Path 'Submenus[0].Title', line 5, position 21.
</code></pre>
<p>The Json file in question looks like this: </p>
<pre><code>{
"Title": "Main Menu",
"Submenus": [
{
"Title": "Submenu 1",
"Contents": "This is an example of the first sub-menu",
"SourceType": "Text"
},
{
"Title": "Submenu 2",
"Contents": "This is the second sub-menu",
"SourceType": "Text"
},
{
"Title": "GitHub System Status",
"Contents": "{\"status\":\"ERROR\",\"body\":\"If you see this, the data failed to load\"}",
"Source": "https://status.github.com/api/last-message.json",
"SourceType": "RestGet"
},
{
"Title": "TF2 Blog RSS",
"Contents": "If you see this message, an error has occurred",
"Source": "http://www.teamfortress.com/rss.xml",
"SourceType": "Rss"
},
{
"Title": "Submenus Test",
"Contents": "Testing the submenu functionality",
"Submenus": [
{
"Title": "Submenu 1",
"Contents": "This is an example of the first sub-menu",
"SourceType": "Text"
},
{
"Title": "Submenu 2",
"Contents": "This is the second sub-menu",
"SourceType": "Text"
}
]
}
],
"SourceType": "Text"
}
</code></pre>
<p>It appears to me that it has trouble deserializing the nested objects, how do I get around that?</p> | 29,124,962 | 2 | 1 | null | 2015-03-18 14:01:10.857 UTC | 9 | 2015-03-18 14:48:56.057 UTC | 2017-05-23 10:30:48.837 UTC | null | -1 | null | 1,351,298 | null | 1 | 19 | c#|json|serialization|json.net | 6,002 | <p>Firstly, <code>SourceType</code> is missed for menu item "Submenus Test" in your json.</p>
<p>Secondly, you shouldn't simply use <code>ToObject</code> because of the <code>Submenus</code> property, which should be handled recursively.</p>
<p>The following <code>ReadJson</code> will work:</p>
<pre><code>public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jObject = JObject.Load(reader);
var sourceType = jObject["SourceType"].Value<string>();
object target = null;
switch (sourceType)
{
case SourceType.File:
target = new FileMenu(); break;
case SourceType.Folder:
target = new FolderMenu(); break;
case SourceType.Json:
target = new JsonMenu(); break;
case SourceType.RestGet:
target = new RestMenu(); break;
case SourceType.Rss:
target = new RssMenu(); break;
case SourceType.Text:
target = new TextMenu(); break;
case SourceType.Url:
target = new UrlMenu(); break;
default:
throw new ArgumentException("Invalid source type");
}
serializer.Populate(jObject.CreateReader(), target);
return target;
}
</code></pre> |
32,588,604 | vim-airline: what is "! trailing[1]" | <p>At the right of my vim-airline display, I have <code>! trailing[1]</code>. </p>
<p>I'm assuming this means trailing whitespace of some sort, but how do I read what vim-airline is telling me and what am I supposed to do?</p> | 32,588,802 | 3 | 2 | null | 2015-09-15 14:25:12.22 UTC | 4 | 2020-12-19 14:27:26.963 UTC | 2015-09-24 07:24:21.313 UTC | null | 1,170,333 | null | 843,542 | null | 1 | 36 | vim|vim-plugin|vim-airline | 15,957 | <p>That means you have a trailing whitespace on the first line (<code>[1]</code>). </p>
<p>You can add to your <code>.vimrc</code> the following:</p>
<pre><code>set list " Display unprintable characters f12 - switches
set listchars=tab:•\ ,trail:•,extends:»,precedes:« " Unprintable chars mapping
</code></pre>
<p>That'll display whitespace chars. You can toggle it with <code>:set invlist</code>.</p> |
5,833,912 | Advantages of using const instead of variables inside methods | <p>Whenever I have local variables in a method, ReSharper suggests to convert them to constants:</p>
<pre><code>// instead of this:
var s = "some string";
var flags = BindingFlags.Public | BindingFlags.Instance;
// ReSharper suggest to use this:
const string s = "some string";
const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
</code></pre>
<p>Given that these are really constant values (and not variables) I understand that ReSharper suggest to change them to const.</p>
<p>But apart from that, is there any other advantage when using const (e.g. better performance) which justifies using <code>const BindingFlags</code> instead of the handy and readable <code>var</code> keyword?</p>
<p>BTW: I just found a similar question here: <a href="https://stackoverflow.com/questions/909681/resharper-always-suggesting-me-to-make-const-string-instead-of-string">Resharper always suggesting me to make const string instead of string</a>, but I think it is more about fields of a class where my question is about local variable/consts.</p> | 5,834,005 | 8 | 0 | null | 2011-04-29 15:17:53.09 UTC | 13 | 2019-03-14 13:37:16.013 UTC | 2017-05-23 12:10:39.227 UTC | null | -1 | null | 19,635 | null | 1 | 92 | c#|coding-style|resharper|constants | 44,255 | <p>The compiler will throw an error if you try to assign a value to a constant, thus possibly preventing you from accidentally changing it.</p>
<p>Also, usually there is a small performance benefit to using constants vs. variables. This has to do with the way they are compiled to the MSIL, per <a href="http://msdn.microsoft.com/en-us/magazine/cc300489.aspx" rel="noreferrer">this MSDN magazine Q&A</a>:</p>
<blockquote>
<p>Now, wherever myInt is referenced in the code, instead of having to do a "ldloc.0" to get the value from the variable, the MSIL just loads the constant value which is hardcoded into the MSIL. <strong>As such, there's usually a small performance and memory advantage to using constants.</strong> However, in order to use them you must have the value of the variable at compile time, and any references to this constant at compile time, even if they're in a different assembly, will have this substitution made.</p>
<p>Constants are certainly a useful tool if you know the value at compile time. If you don't, but want to ensure that your variable is set only once, you can use the readonly keyword in C# (which maps to initonly in MSIL) to indicate that the value of the variable can only be set in the constructor; after that, it's an error to change it. This is often used when a field helps to determine the identity of a class, and is often set equal to a constructor parameter.</p>
</blockquote> |
6,068,955 | jQuery function after .append | <p>How to call a function after jQuery <code>.append</code> is completely done?</p>
<p>Here's an example:</p>
<pre><code>$("#root").append(child, function(){
// Action after append is completly done
});
</code></pre>
<p>The issue: When a complex DOM structure is appended, calculation of new size of the root element within the append function callback is wrong. Assumptions are that the DOM in still not completely loaded, only the first child of the added complex DOM is.</p> | 6,069,060 | 18 | 3 | null | 2011-05-20 07:46:55.22 UTC | 15 | 2019-09-28 11:12:29.497 UTC | 2016-12-06 14:32:05.53 UTC | null | 600,082 | null | 600,082 | null | 1 | 100 | jquery | 173,557 | <p>You've got many valid answers in here but none of them really tells you why it works as it does.</p>
<p>In JavaScript commands are executed one at a time, synchronously in the order they come, unless you explicitly tell them to be asynchronous by using a timeout or interval.</p>
<p>This means that your <code>.append</code> method will be executed and nothing else (disregarding any potential timeouts or intervals that may exist) will execute until that method have finished its job.</p>
<p>To summarize, there's no need for a callback since <code>.append</code> will be run synchronously.</p> |
39,408,793 | Git core.autocrlf line ending default setting | <p>I'm trying to figure out what is the default value for <code>core.autocrlf</code> in Git if the user doesn't change this setting.</p>
<p>I've looked in the docs but can't find this info. Can you please point me in the right direction?</p>
<p>Specifically, on a fresh Git install, would Git automatically convert Windows line endings to Unix when committing to a repo from a Windows system?</p>
<p>Thanks!</p> | 48,230,871 | 5 | 2 | null | 2016-09-09 09:53:56.14 UTC | 5 | 2021-09-09 02:30:14.583 UTC | 2019-11-07 13:40:34.397 UTC | null | 11,808 | null | 570,016 | null | 1 | 46 | git|operating-system|newline | 19,185 | <p>Checking the <a href="https://github.com/git/git/blob/936d1b989416a95f593bf81ccae8ac62cd83f279/environment.c#L48" rel="noreferrer">git source code</a>, core.autocrlf is set to false by default. (And has been since the property's original introduction on <a href="https://github.com/git/git/commit/6c510bee2013022fbce52f4b0ec0cc593fc0cc48" rel="noreferrer">Feb 13, 2007</a>, though it has since been converted from a static value to a constant.)</p>
<p>The Windows installer does require you to pick a value for this property which is explicitly set in the git system config.</p> |
49,130,558 | Postman can't reach localhost | <p>I am in a corporate env so I have to use a proxy to reach servers. This works well in postman and in browsers. What I can't reach is localhost in postman but I can reach localhost in the browser. </p>
<p>I am running Postman for Linux Version 6.0.9. I have tried reaching localhost:9082/rest/myapi.... and 127.0.0.1:9082/rest/myapi with both global proxy and system proxy turned on and with either turned on and with non turned on. In all cases I am not able to reach localhost.</p>
<p>What I get as an response is an error page from the proxy server! Someway the call gets out on the network instead of being kept on my machine.</p>
<p>The postman console:</p>
<p>My request headers are:</p>
<pre><code>Cache-Control →no-cache
Connection →Keep-Alive
Content-Length →986
Content-Type →text/html; charset=utf-8
Pragma →no-cache
Proxy-Connection →Keep-Alive
</code></pre>
<p>My response headers are:</p>
<pre><code>cache-control:"no-cache"
pragma:"no-cache"
content-type:"text/html; charset=utf-8"
proxy-connection:"Keep-Alive"
connection:"Keep-Alive"
content-length:"986"
</code></pre>
<p>My response body is an html page.</p>
<p>How can I make a call to <code>localhost</code> work with postman?</p> | 49,131,070 | 21 | 2 | null | 2018-03-06 12:12:30.54 UTC | 15 | 2022-02-17 09:43:58.31 UTC | 2018-03-06 12:16:20.637 UTC | null | 1,968,182 | null | 1,329,339 | null | 1 | 63 | proxy|postman | 161,891 | <p>I found a temporary solution:</p>
<p>In terminal, go to the directory where postman is installed and add:</p>
<pre><code>machine@dev:~/Documents/Postman$ export NO_PROXY=localhost,127.0.0.1
machine@dev:~/Documents/Postman$ ./Postman
</code></pre>
<p>This will make calls to localhost work.</p>
<p>I found a similar problem on Windows machines <a href="https://github.com/postmanlabs/postman-app-support/issues/3942" rel="noreferrer">here</a></p> |
33,001,237 | Webpack not excluding node_modules | <p>I'm using webpack for a Node framework that I'm building (though I should probably use gulp, admittedly). When I include the EJS module, webpack includes it in the compiled source, even though I explicitly tell it to exclude the node_modules dir.</p>
<pre><code>module.exports = {
context: __dirname,
target: 'node',
// ...
output: {
libraryTarget: 'commonjs'
// ...
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader?{ "stage": 0, "optional": ["runtime"] }'
}
]
}
};
</code></pre>
<p>As you can see, I have a test for JS files, and I tell it to exclude node_modules; why is it ignoring my exclude?</p> | 35,820,388 | 5 | 1 | null | 2015-10-07 19:52:13.543 UTC | 31 | 2021-08-23 22:51:02.727 UTC | null | null | null | null | 1,408,759 | null | 1 | 104 | javascript|webpack | 149,231 | <p>From your config file, it seems like you're only excluding <code>node_modules</code> from being parsed with <code>babel-loader</code>, <strong>but not</strong> from being bundled.</p>
<p>In order to exclude <code>node_modules</code> and native node libraries from bundling, you need to:</p>
<ol>
<li><p>Add <code>target: 'node'</code> to your <code>webpack.config.js</code>. This will define NodeJs as the environment in which the bundle should run. For webpack, it changes the chunk loading behavior, available external modules and generated code style (ie. uses <code>require()</code> for NodeJs) it uses during bundling.</p>
</li>
<li><p>Set the <code>externalPresets</code> of <code>node</code> to <code>true</code>. As of Webpack@5, This configuration will <a href="https://webpack.github.io/docs/configuration.html#target" rel="noreferrer">exclude native node modules</a> (path, fs, etc.) from being bundled.</p>
</li>
<li><p>Use <a href="https://www.npmjs.com/package/webpack-node-externals" rel="noreferrer">webpack-node-externals</a> in order to exclude other <code>node_modules</code>.</p>
</li>
</ol>
<p>So your result config file should look like:</p>
<pre><code>var nodeExternals = require('webpack-node-externals');
...
module.exports = {
...
target: 'node', // use require() & use NodeJs CommonJS style
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
externalsPresets: {
node: true // in order to ignore built-in modules like path, fs, etc.
},
...
};
</code></pre> |
9,014,764 | Have a parent class's method access the subclass's constants | <p>For example:</p>
<pre><code>class Animal
def make_noise
print NOISE
end
end
class Dog < Animal
NOISE = "bark"
end
d = Dog.new
d.make_noise # I want this to print "bark"
</code></pre>
<p>How do I accomplish the above? Currently it says </p>
<pre><code>uninitialized constant Animal::NOISE
</code></pre> | 9,014,799 | 5 | 0 | null | 2012-01-26 06:48:11.23 UTC | 3 | 2016-12-16 20:07:43.16 UTC | 2012-01-26 06:54:03.94 UTC | null | 405,017 | null | 553,044 | null | 1 | 28 | ruby|constants | 8,320 | <p>I think that you don't really want a constant; I think that you want an instance variable on the class:</p>
<pre><code>class Animal
@noise = "whaargarble"
class << self
attr_accessor :noise
end
def make_noise
puts self.class.noise
end
end
class Dog < Animal
@noise = "bark"
end
a = Animal.new
d = Dog.new
a.make_noise #=> "whaargarble"
d.make_noise #=> "bark"
Dog.noise = "WOOF"
d.make_noise #=> "WOOF"
a.make_noise #=> "whaargarble"
</code></pre>
<p>However, if you are sure that you want a constant:</p>
<pre><code>class Animal
def make_noise
puts self.class::NOISE
# or self.class.const_get(:NOISE)
end
end
</code></pre> |
9,567,882 | Sobel filter kernel of large size | <p>I am using a sobel filter of size 3x3 to calculate the image derivative. Looking at some articles on the internet, it seems that kernels for sobel filter for size 5x5 and 7x7 are also common, but I am not able to find their kernel values. </p>
<p>Could someone please let me know the kernel values for sobel filter of size 5x5 and 7x7? Also, if someone could share a method to generate the kernel values, that will be much useful.</p>
<p>Thanks in advance.</p> | 9,567,940 | 10 | 0 | null | 2012-03-05 13:59:30.26 UTC | 22 | 2021-08-17 06:44:50.42 UTC | 2016-04-06 14:09:05.207 UTC | null | 253,056 | null | 938,221 | null | 1 | 49 | image-processing|computer-vision|edge-detection|sobel | 50,305 | <p><em>UPDATE 23-Apr-2018: it seems that the kernels defined in the link below are not true Sobel kernels (for 5x5 and above) - they may do a reasonable job of edge detection, but they should not be called Sobel kernels. See <a href="https://stackoverflow.com/a/41065243/253056">Daniel’s answer</a> for a more accurate and comprehensive summary. (I will leave this answer here as (a) it is linked to from various places and (b) accepted answers can not easily be deleted.)</em></p>
<p><strike>Google seems to turn up plenty of results, e.g.
<a href="http://rsbweb.nih.gov/nih-image/download/user-macros/slowsobel.macro" rel="nofollow noreferrer">http://rsbweb.nih.gov/nih-image/download/user-macros/slowsobel.macro</a> suggests the following kernels for 3x3, 5x5, 7x7 and 9x9:</p>
<p>3x3:</p>
<pre><code>1 0 -1
2 0 -2
1 0 -1
</code></pre>
<p>5x5:</p>
<pre><code>2 1 0 -1 -2
3 2 0 -2 -3
4 3 0 -3 -4
3 2 0 -2 -3
2 1 0 -1 -2
</code></pre>
<p>7x7:</p>
<pre><code>3 2 1 0 -1 -2 -3
4 3 2 0 -2 -3 -4
5 4 3 0 -3 -4 -5
6 5 4 0 -4 -5 -6
5 4 3 0 -3 -4 -5
4 3 2 0 -2 -3 -4
3 2 1 0 -1 -2 -3
</code></pre>
<p>9x9:</p>
<pre><code>4 3 2 1 0 -1 -2 -3 -4
5 4 3 2 0 -2 -3 -4 -5
6 5 4 3 0 -3 -4 -5 -6
7 6 5 4 0 -4 -5 -6 -7
8 7 6 5 0 -5 -6 -7 -8
7 6 5 4 0 -4 -5 -6 -7
6 5 4 3 0 -3 -4 -5 -6
5 4 3 2 0 -2 -3 -4 -5
4 3 2 1 0 -1 -2 -3 -4
</code></pre>
<p></strike></p> |
9,373,104 | Why doesn't ruby support method overloading? | <p>Instead of supporting method overloading Ruby overwrites existing methods. Can anyone explain why the language was designed this way?</p> | 9,373,811 | 9 | 0 | null | 2012-02-21 06:22:49.65 UTC | 40 | 2022-06-29 09:22:03.723 UTC | 2014-06-20 16:49:12.267 UTC | null | 183,380 | null | 489,559 | null | 1 | 153 | ruby | 53,089 | <p>Method overloading can be achieved by declaring two methods with the same name and different signatures. These different signatures can be either,</p>
<ol>
<li>Arguments with different data types, eg: <code>method(int a, int b) vs method(String a, String b)</code></li>
<li>Variable number of arguments, eg: <code>method(a) vs method(a, b)</code></li>
</ol>
<p>We cannot achieve method overloading using the first way because there is no data type declaration in ruby(<strong>dynamic typed language</strong>). So the only way to define the above method is <code>def(a,b)</code></p>
<p>With the second option, it might look like we can achieve method overloading, but we can't. Let say I have two methods with different number of arguments,</p>
<pre><code>def method(a); end;
def method(a, b = true); end; # second argument has a default value
method(10)
# Now the method call can match the first one as well as the second one,
# so here is the problem.
</code></pre>
<p>So ruby needs to maintain one method in the method look up chain with a unique name.</p> |
31,109,345 | Android - How to Convert String to utf-8 in android | <p>I can't convert a String to UTF-8 in android. please help me!!</p>
<pre><code>s1=URLEncoder.encode("臺北市")
</code></pre>
<p>result : <code>%EF%BF%BDO%EF%BF%BD_%EF%BF%BD%EF%BF%BD</code></p>
<p>But "<code>臺北市</code>" should be encoded as "<code>%E8%87%BA%E5%8C%97%E5%B8%82</code>"</p> | 31,109,646 | 4 | 1 | null | 2015-06-29 06:45:49.923 UTC | 2 | 2019-01-18 22:34:59.693 UTC | 2017-03-30 14:38:31.41 UTC | null | 5,530,965 | null | 5,059,958 | null | 1 | 9 | java|android|utf-8|encode | 64,065 | <p>In <a href="http://developer.android.com/reference/java/net/URLEncoder.html">http://developer.android.com/reference/java/net/URLEncoder.html</a> you can read that the you used is deprecated and that you should use <code>static String encode(String s, String charsetName)</code></p>
<p>So <code>URLEncoder.encode("臺北市", "utf-8")</code> should do the trick.</p> |
47,238,245 | Stop swiper slide autoplay on mouse enter and start autoplay on mouse leave | <p>How to stop swiper slide autoplay on mouse enter and start autoplay on mouse leave? I have tried <code>.stopAutoplay()</code> and <code>.startAutoplay()</code> function but not worked for me.</p>
<p>thank you here is code. and i face console error </p>
<blockquote>
<p>Uncaught TypeError: swiper .startAutoplay is not a function</p>
</blockquote>
<pre><code> var swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true,
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
spaceBetween: 0,
loop: true,
effect: 'slide',
longSwipes: true,
autoplay:2000,
autoplayDisableOnInteraction:true,
});
$(".swiper-container").mouseenter(function(){
swiper.stopAutoplay();
});
$(".swiper-container").mouseleave(function(){
swiper.startAutoplay();
});
</code></pre> | 47,238,361 | 8 | 1 | null | 2017-11-11 13:11:01.663 UTC | 8 | 2022-04-15 17:55:27.82 UTC | 2018-09-05 18:40:44.843 UTC | null | 3,731,614 | null | 5,287,215 | null | 1 | 9 | javascript|jquery|swiper.js | 59,336 | <p>You need to use the option <code>disableOnInteraction: true</code> rather than binding the events yourself see here for <a href="http://idangero.us/swiper/api/#autoplay" rel="noreferrer">documentation</a>.</p>
<p>Optionally you can use the following for autoplay start stop </p>
<ul>
<li><p><code>swiper.autoplay.start();</code></p></li>
<li><p><code>swiper.autoplay.stop();</code></p></li>
</ul>
<p><strong>Edit</strong> </p>
<p>Your mistake is how you are getting the instance for swiper. see below for demo</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
new Swiper('.swiper-container', {
speed: 400,
spaceBetween: 100,
autoplay: true,
disableOnInteraction: true,
});
var mySwiper = document.querySelector('.swiper-container').swiper
$(".swiper-container").mouseenter(function() {
mySwiper.autoplay.stop();
console.log('slider stopped');
});
$(".swiper-container").mouseleave(function() {
mySwiper.autoplay.start();
console.log('slider started again');
});
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.swiper-slide {
text-align: center;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.0.5/js/swiper.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.0.5/css/swiper.css" rel="stylesheet" />
<!-- Slider main container -->
<div class="swiper-container">
<!-- Additional required wrapper -->
<div class="swiper-wrapper">
<!-- Slides -->
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
<div class="swiper-slide">Slide 4</div>
</div>
<!-- If we need pagination -->
<div class="swiper-pagination"></div>
<!-- If we need navigation buttons -->
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
<!-- If we need scrollbar -->
<div class="swiper-scrollbar"></div>
</div></code></pre>
</div>
</div>
</p> |
22,774,529 | What is the safest way to removing Python framework files that are located in different place than Brew installs | <p>I want to remove a Python installed in location that brew complains about, when I run <code>brew doctor</code></p>
<blockquote>
<p><strong>Warning:</strong> Python is installed at /Library/Frameworks/Python.framework</p>
</blockquote>
<p><strong>What is the best way?</strong></p>
<p><strong>Here are more details / research:</strong></p>
<p>The message from the brew git <a href="https://github.com/Homebrew/homebrew/wiki/Homebrew-and-Python" rel="noreferrer">website</a>:</p>
<blockquote>
<p><strong>Important:</strong> If you choose to install a Python which isn't either of
these two (system Python or brewed Python), the Homebrew team can only
provide limited support.</p>
</blockquote>
<p><strong>I want to make sure I am not missing anything before I remove the extra python libary.</strong>
Specifically, I want to remove the entire Python.framework, those files located here.
/Library/Frameworks/Python.framework/</p>
<p>I have Python 2.7.5 installed natively with Mavericks that I'll use instead - located in the path below. (The difference being -- I believe -- that its put in the <strong>root /System folder</strong> instead of the <strong>root /Library folder</strong>.) The good, native location is here:
<code>/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python</code></p>
<p>and I already installed python 3.x with <code>brew install python3</code>, which put it here:</p>
<pre><code>==> Summary
/usr/local/Cellar/python3/3.4.0 : 5076 files, 85M, built in 112 seconds
</code></pre>
<p>Can I just delete these files or are their consequences (beyond having to relink)?
<code>/Library/Frameworks/Python.framework/</code></p>
<p>Here are steps to remove python from a <a href="https://stackoverflow.com/questions/3819449/how-to-uninstall-python-2-7-on-a-mac-os-x-10-6-4/3819829#3819829">stackoverflow question in 2010</a> and a <a href="https://stackoverflow.com/questions/22255579/homebrew-brew-doctor-warning-about-library-frameworks-python-framework-even-wi">similar question here</a></p>
<p>Is that approach still sound? Is there anything I should be aware of?</p> | 22,800,774 | 1 | 1 | null | 2014-04-01 00:11:09.9 UTC | 35 | 2017-12-20 21:27:53.01 UTC | 2017-05-23 12:02:21.55 UTC | null | -1 | null | 2,283,965 | null | 1 | 52 | python|macos|homebrew|brew-doctor | 94,766 | <p>I'll self-answer. I went through steps and it's straight forward. Pycharms (the IDE I'm use) automatically found the new libraries too. Here are the steps I followed to remove the extra Python libraries on Mavericks that were not native to it and not installed by brew.</p>
<p><strong>Step 1:</strong>
The native Python 2.7.x version lives here <code>/System/Library/Frameworks/Python.framework/Versions/2.7</code> (or 2.6, etc), so you can remove any Python that got installed elsewhere.</p>
<p><code>sudo rm -rf /System/Library/Frameworks/Python.framework/</code></p>
<p>Or, according to this <a href="http://java.dzone.com/articles/good-clean-python-install" rel="nofollow noreferrer">article</a>, you should brew install both python 2.7 and python 3.x,
and avoid using system python in Mavericks.</p>
<p><strong>Step 2:</strong>
Remove python in Applications directory (the one where all your apps are). </p>
<p>cd into folder <code>/Applications</code> and <code>ls | grep Python</code> to see what have. </p>
<p>Then remove:
<code>sudo rm -rf "Python 3.3"</code></p>
<p><strong>Step 3:</strong></p>
<p><code>>>> brew prune</code></p>
<p>sample output:</p>
<blockquote>
<p>Pruned 0 dead formula Pruned 46 symbolic links from /usr/local</p>
</blockquote>
<p><strong>Step 4:</strong> Run steps recommended by <code>brew doctor</code></p>
<p><code>sudo brew link python3</code></p>
<p>Sample output</p>
<blockquote>
<p>Linking /usr/local/Cellar/python3/3.4.0... 19 symlinks created</p>
</blockquote> |
22,904,216 | What keeps a php session alive? | <p>Are sessions only kept alive each time you access a page with <code>session_start();</code> or do other pages keep it alive too?</p>
<p>Example (with <strong>30 minute</strong> timeout):</p>
<h2>1</h2>
<blockquote>
<p>user accesses page with session_start();<br>
25 mins later they access another session_start();<br>
page session stays alive</p>
</blockquote>
<h1>2</h1>
<blockquote>
<p>user accesses page with session_start();<br>
25 mins later they access a non-session_start(); page<br>
session stays alive</p>
</blockquote>
<p>Is <strong>2</strong> also true ?</p> | 22,904,338 | 7 | 2 | null | 2014-04-07 05:25:46.573 UTC | 3 | 2015-05-17 15:31:29.51 UTC | 2014-04-07 06:47:51.287 UTC | null | 1,372,424 | null | 952,170 | null | 1 | 34 | php|session | 10,814 | <p>There is always a session cookie set in your browser whenever you access a page which has <code>session_start()</code>. The cookie name will <code>PHPSESSID</code> if the website is using PHP(although the name can be changed). This session cookie contains a session id which helps the browser to maintain that session with the server.</p>
<p>You can check manually by browsing any website which has your session and then delete your browser cookies, your session will be lost.</p>
<p><strong>In your case both 1 & 2 are correct.</strong></p>
<p>2 is correct because the user already has accessed a page which has <code>session_start()</code> and your session id will be set for the next 30 mins and it will be present even if you accesse a page which does not have a session.</p>
<p><strong>NOTE:</strong> But the page which you will be visiting if contains <code>session_destroy()</code>, your session will be destroyed.</p> |
7,213,549 | Long Polling/HTTP Streaming General Questions | <p>I'm trying to make a theoretical web chat application with <a href="/questions/tagged/php" class="post-tag" title="show questions tagged 'php'" rel="tag">php</a> and <a href="/questions/tagged/jquery" class="post-tag" title="show questions tagged 'jquery'" rel="tag">jquery</a>, I've read about long polling and http streaming, and I managed to apply most principles introduced in the articles. However, there are 2 main things I still can't get my head around.</p>
<h2>With Long Polling</h2>
<ul>
<li>How will the server know when an update have been sent? will it need to query the databse continually or is there a better way?</li>
</ul>
<h2>With HTTP Streaming</h2>
<ul>
<li>How do I check for the results during the Ajax connection is still active? I'm aware of jQuery's <code>success</code> function for ajax calls, but how do I check the data <strong>while</strong> the connection is still ongoing?</li>
</ul>
<p>I'll appreciate any and all answers, thanks in advance.</p> | 7,214,483 | 2 | 3 | null | 2011-08-27 09:05:34.187 UTC | 12 | 2011-09-12 15:33:27.757 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 871,050 | null | 1 | 19 | php|jquery|comet|long-polling|http-streaming | 6,913 | <p>Yeah, the Comet-like techniques usually blowing up the brain in the beginning -- just making you think in a different way. And another problem is there are not that much resources available for PHP, cuz everyone's doing their Comet in node.js, Python, Java, etc.</p>
<p>I'll try to answer your questions, hope it would shed some light on this topic for people.</p>
<blockquote>
<p>How will the server know when an update have been sent? will it need to query the databse continually or is there a better way?</p>
</blockquote>
<p>The answer is: in the most general case you should use a message queue (MQ). RabbitMQ or the Pub/Sub functionality built into the Redis store may be a good choices, though there are many competing solutions on the market available such as ZeroMQ, Beanstalkd, etc.</p>
<p>So instead of continuous querying your database, you can just <em>subscribe</em> for an MQ-event and just hang until someone else will <em>publish</em> a message you subscribed for and MQ will wake you up and send a message. The chat app is a very good use case to understand this functionality.</p>
<p>Also I have to mention that if you would search for Comet-chat implementations in other languages, you might notice simple ones not using MQ. So how do they exchange the information then? The thing is such solutions are usually implemented as standalone single-threaded asynchronous servers, so they can store all connections in a thread local array (or something similar), handle many connections in a single loop and just pick a one and notify when needed. Such asynchronous server implementations are a modern approach that fits Comet-technique really great. However you're most likely implementing your Comet on top of mod_php or FastCGI, in this case this simple approach is not an option for you and you should use MQ.</p>
<p>This could still be very useful to understand how to implement a standalone asynchronous Comet-server to handle many connections in a single thread. Recent versions of PHP support Libevent and Socket Streams, so it is possible to implement such kind of server in PHP as well. There's also an <a href="http://php.net/manual/en/libevent.examples.php#99127" title="example">example</a> available in PHP documentation.</p>
<blockquote>
<p>How do I check for the results during the Ajax connection is still active? I'm aware of jQuery's success function for ajax calls, but how do I check the data while the connection is still ongoing?</p>
</blockquote>
<p>If you're doing your long-running polls with a usual Ajax technique such as plain XHR, jQuery Ajax, etc. you don't have an easy way to transmit several responses in a single Ajax request. As you mentioned you only have 'success' handler to deal with the response in whole and not with its part. As a workaround people send only a single response per request and process it in a 'success' handler, after that they just open a new long-poll request. This is just how HTTP-protocol works.</p>
<p>Also should be mentioned that actually there are workaround to implement streaming-like functionality using various techniques using techniques such as infinitely long page in a hidden <code>IFRAME</code> or using multipart HTTP-responses. Both of those methods are certain drawbacks (the former one is considered unreliable and sometimes could produce unwanted browser behavior such as infinite loading indicator and the latter one leaks consistent and straightforward cross-browser support, however certain applications still are known to successfully rely on that mechanism falling back to long-polling when the browser can't properly handle multipart responses).</p>
<p>If you'd like to handle multiple responses per single request/connection in a reliable way you should consider using a more advanced technology such as WebSocket which is supported by the most current browsers or on any platform that supports raw sockets (such as Flash or if you develop for a mobile app for instance).</p>
<blockquote>
<p>Could you please elaborate more on message queues?</p>
</blockquote>
<p><a href="http://en.wikipedia.org/wiki/Message_queue%20%22Message%20queue">Message Queue</a> is a term that describes a standalone (or built-in) implementation of the <a href="http://en.wikipedia.org/wiki/Observer_pattern">Observer pattern</a> (also known as 'Publish/Subscribe' or simply PubSub). If you develop a big application, having one is <em>very</em> useful -- it allows you to decouple different parts of your system, implement event-driven asynchronous design and make your life much easier, especially in a heterogeneous systems. It has many applications to the real-world systems, I'll mention just couple of them:</p>
<ul>
<li>Task queues. Let's say we're writing our own YouTube and need to convert users' video files in the background. We should obviously have a webapp with the UI to upload a movie and some fixed number of worker processes to convert the video files (maybe we would even need a number of dedicated servers where our workers only will leave). Also we would probably have to write our workers in C to ensure better performance. All we have to do is just setup a message queue server to collect and deliver video-conversion tasks from the webapp to our workers. When the worker spawns it connects to the MQ and goes idle waiting for a new tasks. When someone uploads a video file the webapp connects to the MQ and publishes a message with a new job. Powerful MQs such as <a href="http://www.rabbitmq.com/">RabbitMQ</a> can equally distribute tasks among number of workers connected, keep track of what tasks had been completed, ensure nothing will get lost and will provide fail-over and even admin UI to browse current tasks pending and stats.</li>
<li>Asynchronous behavior. Our Comet-chat is a good example. Obviously we don't want to periodically poll our database all time (what's the use of Comet then? -- Not big difference of doing periodical Ajax-requests). We would rather need someone to notify us when a new chat-message appears. And a message queue is that someone. Let's say we're using <a href="http://redis.io/">Redis</a> key/value store -- this is a really great tool that provides <a href="http://redis.io/topics/pubsub">PubSub</a> implementation among its data store features. The simplest scenario may look like following:
<ol>
<li>After someone enters the chat room a new Ajax long poll request is being made.</li>
<li>Request handler on the server side issues the command to Redis to subscribe a 'newmessage' channel.</li>
<li>Once someone enters a message into his chat the server-side handler publishes a message into the Redis' 'newmessage' topic.</li>
<li>Once a message is published, Redis will immediately notify all those pending handlers which subscribed to that channel before.</li>
<li>Upon notification PHP-code that keeps long-poll request open, can return the request with a new chat message, so all users will be notified. They can read new messages from the database at that moment, or the messages may be transmitted directly inside message payload.</li>
</ol></li>
</ul>
<p>I hope my illustration is easy to understand, however message queues is a very broad topic, so refer to the resources mentioned above for further reading.</p> |
7,029,904 | Looking for the Code Converter which converts C# to Java | <p>Can anybody help me by suggesting the name of an converter which converts C# code to Java code. Actually, I have a tool which is written in C# code and I am trying to modify it. As I have no idea about C# and .NET framework, it seems difficult to me to convert the large code by my own. I found from some web information that there exist some tools which can convert C# to Java (may not be properly, however they can). Can anybody help me by suggesting some name of those tools.</p> | 7,030,553 | 2 | 9 | null | 2011-08-11 16:58:09.987 UTC | 5 | 2015-07-27 16:15:01.207 UTC | 2015-07-27 16:15:01.207 UTC | null | 1,768,232 | null | 772,399 | null | 1 | 20 | java|c#|code-conversion | 60,646 | <p><strong>Disclaimer:</strong> <em>No tool is perfect.</em></p>
<p>However, if you still want to try then there are these converters available:</p>
<ul>
<li><a href="http://www.cs2j.com/" rel="noreferrer">CS2J</a></li>
<li><a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=14349" rel="noreferrer">JCLA</a> : Convert Java-language code to C#</li>
<li><a href="http://dev.mainsoft.com/Default.aspx?tabid=130#What%20is%20Grasshopper?" rel="noreferrer">Grasshopper</a></li>
<li><a href="http://csharpjavamerger.org/" rel="noreferrer">CSharpJavaMerger</a></li>
<li><a href="http://www.tangiblesoftwaresolutions.com/Product_Details/CSharp_to_Java_Converter_Details.html" rel="noreferrer">Tangible Software C# to Java Converter</a></li>
</ul>
<p>Not a converter but a bridge between .NET and the JVM:</p>
<ul>
<li><a href="http://jni4net.sf.net/" rel="noreferrer">JNI4NetBridge</a></li>
</ul> |
7,314,849 | What is purpose of the property "private" in package.json? | <p>I'm learning node.js and express, I am wondering what is the property "private" in ./package.json file used for?</p> | 7,314,961 | 2 | 0 | null | 2011-09-06 04:14:04.443 UTC | 18 | 2022-01-28 12:54:51.743 UTC | 2019-01-31 12:38:22.463 UTC | null | 5,812,238 | null | 501,963 | null | 1 | 227 | node.js|package.json | 76,192 | <p>From the <a href="https://docs.npmjs.com/cli/v7/configuring-npm/package-json#private" rel="noreferrer">NPM docs on <code>package.json</code></a>:</p>
<blockquote>
<p><code>private</code></p>
<p>If you set <code>"private": true</code> in your package.json, then npm will refuse to publish it.</p>
<p>This is a way to prevent accidental publication of private repositories.</p>
</blockquote> |
35,684,436 | Testing file uploads in Flask | <p>I'm using <a href="https://pythonhosted.org/Flask-Testing/" rel="noreferrer">Flask-Testing</a> for my Flask integration tests. I've got a form that has a file upload for a logo that I'm trying to write tests for but I keep getting an error saying: <code>TypeError: 'str' does not support the buffer interface</code>.</p>
<p>I'm using Python 3. The closest answer I have found is <a href="https://stackoverflow.com/questions/20080123/testing-file-upload-with-flask-and-python-3">this</a> but it's not working for me.</p>
<p>This is what one of my many attempts looks like:</p>
<pre><code>def test_edit_logo(self):
"""Test can upload logo."""
data = {'name': 'this is a name', 'age': 12}
data['file'] = (io.BytesIO(b"abcdef"), 'test.jpg')
self.login()
response = self.client.post(
url_for('items.save'), data=data, follow_redirects=True)
})
self.assertIn(b'Your item has been saved.', response.data)
advert = Advert.query.get(1)
self.assertIsNotNone(item.logo)
</code></pre>
<p>How does one test a file upload in Flask?</p> | 35,712,344 | 4 | 1 | null | 2016-02-28 15:33:39.437 UTC | 12 | 2022-02-16 17:39:57.63 UTC | 2020-02-04 23:06:08.593 UTC | null | 400,617 | null | 1,069,232 | null | 1 | 48 | python|flask | 28,381 | <p>The issue ended up not being that when one adds <code>content_type='multipart/form-data'</code> to the <code>post</code> method it expect all values in <code>data</code> to either be files or strings. There were integers in my data dict which I realised thanks to <a href="https://stackoverflow.com/questions/35684436/testing-file-uploads-in-flask/35707921?noredirect=1#comment59099614_35707921">this</a> comment.</p>
<p>So the end solution ended up looking like this:</p>
<pre><code>def test_edit_logo(self):
"""Test can upload logo."""
data = {'name': 'this is a name', 'age': 12}
data = {key: str(value) for key, value in data.items()}
data['file'] = (io.BytesIO(b"abcdef"), 'test.jpg')
self.login()
response = self.client.post(
url_for('adverts.save'), data=data, follow_redirects=True,
content_type='multipart/form-data'
)
self.assertIn(b'Your item has been saved.', response.data)
advert = Item.query.get(1)
self.assertIsNotNone(item.logo)
</code></pre> |
21,065,938 | Read a single column of a CSV and store in an array | <p>What is the best way to read from a csv, but only one specific column, like <code>title</code>?</p>
<pre><code>ID | date| title |
-------------------
1| 2013| abc |
2| 2012| cde |
</code></pre>
<p>The column should then be stored in an array like this:</p>
<pre><code>data = ["abc", "cde"]
</code></pre>
<p>This is what I have so far, with <a href="http://pandas.pydata.org/" rel="noreferrer">pandas</a>:</p>
<pre><code>data = pd.read_csv("data.csv", index_col=2)
</code></pre>
<p>I've looked into <a href="https://stackoverflow.com/questions/16503560/read-specific-columns-from-csv-file-with-python-csv">this thread</a>. I still get an <code>IndexError: list index out of range</code>.</p>
<p><strong>EDIT</strong>:</p>
<p>It's not a table, it's comma seperated like this:</p>
<pre><code>ID,date,title
1,2013,abc
2,2012,cde
</code></pre> | 21,066,850 | 3 | 2 | null | 2014-01-11 18:07:42.15 UTC | 4 | 2014-01-12 15:10:43.253 UTC | 2017-05-23 11:45:24.007 UTC | null | -1 | null | 1,344,855 | null | 1 | 12 | python|csv|pandas | 47,797 | <p>One option is just to read in the entire csv, then select a column:</p>
<pre><code>data = pd.read_csv("data.csv")
data['title'] # as a Series
data['title'].values # as a numpy array
</code></pre>
<p>As @dawg suggests, you can use the usecols argument, if you also use the squeeze argument to avoid some hackery flattening the values array...</p>
<pre><code>In [11]: titles = pd.read_csv("data.csv", sep=',', usecols=['title'], squeeze=True)
In [12]: titles # Series
Out[12]:
0 abc
1 cde
Name: title, dtype: object
In [13]: titles.values # numpy array
Out[13]: array(['abc', 'cde'], dtype=object)
</code></pre> |
18,727,110 | SQL Server Management Studio - Login failed for user (.Net SqlClient Data Provider) | <p>I have very strange problem.</p>
<p>When I try to connect my database (located on shared SQL Server) with SQL Server Management Studio 2008/2012. This database which is hosted by a company for web hosting, I receive this very strange error:</p>
<blockquote>
<p>Cannot connect to tango.rdb.superhosting.bg.</p>
<p>Login failed for user 'database_administrator'. (.Net SqlClient Data Provider)</p>
<p>Server Name: tango.rdb.superhosting.bg<br>
Error Number: 18456<br>
Severity: 14<br>
State: 1<br>
Line Number: 65536 </p>
</blockquote>
<p>Near some weeks ago everything worked perfect and I did not have any problems with connecting the SQL Server with SQL Server Management Studio 2008.</p>
<p>When I faced this problem, I installed SQL Server Management Studio 2012 and result is the same.</p>
<p>But with the absolute the same credentials I can connect to my database on the same server using VS2010 or Toad for SQL.</p>
<p>Do you have any suggestions?</p>
<p>Thanks in advance!</p> | 18,729,271 | 1 | 1 | null | 2013-09-10 19:16:33.963 UTC | 5 | 2016-12-30 06:07:43.647 UTC | 2013-09-10 20:29:58.06 UTC | null | 13,302 | null | 1,586,697 | null | 1 | 11 | ssms | 42,723 | <p>This is probably an issue of an orphaned user.</p>
<p>The login 'database_administrator' can either be:</p>
<ul>
<li>On the Database itself. Just navigate to Logins under the database in SSMS.</li>
<li>Or, under the Server -> Security Logins.</li>
</ul>
<p>What I usually do is:</p>
<ol>
<li>Remove the Login that exists under the database</li>
<li>Add the Login under the server level Security</li>
<li>Give rights to that user to the particular database it needs</li>
</ol>
<p>There are a bunch of ways to solve orphaned users, but that is usually what I do.</p> |
28,045,787 | How many decimal places does the primitive float and double support? | <p>I have read that double stores 15 digits and float stores 7 digits.</p>
<p>My question is, are these numbers the number of decimal places supported or total number of digits in a number?</p> | 28,045,815 | 4 | 1 | null | 2015-01-20 12:48:39.893 UTC | 2 | 2015-01-20 14:10:02.523 UTC | null | null | null | null | 521,180 | null | 1 | 16 | c++ | 51,375 | <p>Those are the total number of "significant figures" if you will, counting from left to right, regardless of where the decimal point is. Beyond those numbers of digits, accuracy is not preserved.</p>
<p>The counts you listed are for the base 10 representation.</p> |
2,294,250 | .NET MVC - How to assign a class to Html.LabelFor? | <p>This code</p>
<pre><code><%= Html.LabelFor(model => model.Name) %>
</code></pre>
<p>produces this</p>
<pre><code><label for="Name">Name</label>
</code></pre>
<p>But I want this</p>
<pre><code><label for="Name" class="myLabel">Name</label>
</code></pre>
<p>How do you do that?</p> | 2,294,335 | 3 | 0 | null | 2010-02-19 05:25:22.423 UTC | 12 | 2013-11-25 20:33:07.28 UTC | 2012-08-03 12:09:40.077 UTC | null | 457,500 | null | 36,036 | null | 1 | 69 | asp.net-mvc | 69,309 | <p>Okay, looking at the source (System.Web.Mvc.Html.LabelExtensions.cs) for this method, there doesn't seem to be a way to do this with an HtmlHelper in ASP.NET MVC 2. I think your best bet is to either create your own HtmlHelper or do the following for this specific label:</p>
<pre><code><label for="Name" class="myLabel"><%= Model.Name %></label>
</code></pre> |
8,518,750 | To show only file name without the entire directory path | <p><code>ls /home/user/new/*.txt</code> prints all txt files in that directory. However it prints the output as follows:</p>
<pre><code>[me@comp]$ ls /home/user/new/*.txt
/home/user/new/file1.txt /home/user/new/file2.txt /home/user/new/file3.txt
</code></pre>
<p>and so on.</p>
<p>I want to run the <code>ls</code> command not from the <code>/home/user/new/</code> directory thus I have to give the full directory name, yet I want the output to be only as</p>
<pre><code>[me@comp]$ ls /home/user/new/*.txt
file1.txt file2.txt file3.txt
</code></pre>
<p>I don't want the entire path. Only filename is needed. This issues has to be solved using ls command, as its output is meant for another program.</p> | 8,518,818 | 13 | 1 | null | 2011-12-15 10:41:11.743 UTC | 21 | 2022-02-01 18:34:51.943 UTC | 2015-07-02 15:00:01.653 UTC | null | 1,288 | null | 1,099,285 | null | 1 | 94 | shell|unix|directory|ls | 213,244 | <p><code>ls whateveryouwant | xargs -n 1 basename</code></p>
<p>Does that work for you?</p>
<p>Otherwise you can <code>(cd /the/directory && ls)</code> (yes, parentheses intended)</p> |
19,323,678 | Error in resolving buildtime dependencies while installing CloudStack on ubuntu. | <p>I am installing cloudstack on ubuntu and it uses maven to resolve its dependencies. I am getting the following errors when am running the command <code>mvn -P deps</code> </p>
<pre><code>[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR] The project org.apache.cloudstack:cloudstack:4.2.0 (/home/cloud/apache-cloudstack-4.2.0-src/pom.xml) has 1 error
[ERROR] Non-resolvable parent POM: Could not transfer artifact org.apache:apache:pom:11 from/to central (http://repo.maven.apache.org/maven2): repo.maven.apache.org: Name or service not known and 'parent.relativePath' points at wrong local POM @ line 14, column 11: Unknown host repo.maven.apache.org: Name or service not known -> [Help 2]
[ERROR]
</code></pre>
<p>I have searched the error and tried a number of changes in pom.xml but i am not getting the solution. I dont know whats causing the error.</p>
<p>any suggestion or slightest help will be acknowledged. Thank you. </p> | 19,363,885 | 4 | 1 | null | 2013-10-11 17:10:30.583 UTC | 2 | 2016-10-25 09:53:44.46 UTC | 2013-10-13 12:17:54.353 UTC | null | 1,521,627 | null | 2,871,856 | null | 1 | 12 | maven|apache-cloudstack | 38,970 | <p>This is a <strong>networking</strong> issue: </p>
<p>Your build machine cannot access <a href="http://repo.maven.apache.org/maven2" rel="nofollow noreferrer">http://repo.maven.apache.org/maven2</a></p>
<p>Use <code>wget</code> at command line to check if you can access the website. E.g.</p>
<pre><code>root@mgmtserver:~/cm# wget http://repo.maven.apache.org/maven2
--2013-10-14 16:33:24-- http://repo.maven.apache.org/maven2
Resolving repo.maven.apache.org (repo.maven.apache.org)... 185.31.19.184, 185.31.19.185
Connecting to repo.maven.apache.org (repo.maven.apache.org)|185.31.19.184|:80... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: http://central.maven.org/maven2/ [following]
--2013-10-14 16:33:24-- http://central.maven.org/maven2/
Resolving central.maven.org (central.maven.org)... 185.31.19.184, 185.31.19.185
Reusing existing connection to repo.maven.apache.org:80.
HTTP request sent, awaiting response... 200 OK
Length: 967 [text/html]
Saving to: `maven2'
100%[=====================================================>] 967 --.-K/s in 0s
2013-10-14 16:33:24 (74.4 MB/s) - `maven2' saved [967/967]
</code></pre>
<p>Reasons why <code>wget</code> might fail: </p>
<ol>
<li>the Maven repo is temporarily down. Wait until it works.</li>
<li>no network adapter on your build machine. Check that it has network access.</li>
<li>your proxy settings are incorrect. <a href="https://stackoverflow.com/a/15334627/939250">Try this solution</a>, or <a href="http://maven.apache.org/guides/mini/guide-proxies.html" rel="nofollow noreferrer">the Maven mini-guide proxy settings</a></li>
</ol>
<p><strong>Background:</strong></p>
<p>Apache CloudStack's POM.xml inherits predefined values from the <a href="http://maven.apache.org/pom/asf/" rel="nofollow noreferrer">Apache Software Foundation Parent POM</a>. As a result, a Maven build first downloads the required POM from a network location, and Maven stores it locally in the <a href="http://maven.apache.org/guides/introduction/introduction-to-repositories.html" rel="nofollow noreferrer">Maven repository</a>, which is a kind of local cache. </p>
<p><strong>Final remarks:</strong></p>
<p>If you're curious, the source for the POM being download is <a href="http://search.maven.org/#browse%7C1381669572" rel="nofollow noreferrer">here</a>.</p> |
58,896,661 | SwiftUI create image slider with dots as indicators | <p>I want to create a scroll view/slider for images. See my example code:</p>
<pre><code>ScrollView(.horizontal, showsIndicators: true) {
HStack {
Image(shelter.background)
.resizable()
.frame(width: UIScreen.main.bounds.width, height: 300)
Image("pacific")
.resizable()
.frame(width: UIScreen.main.bounds.width, height: 300)
}
}
</code></pre>
<p><strong>Though this enables the user to slide, I want it a little different (similar to a PageViewController in UIKit). I want it to behave like the typical image slider we know from a lot of apps with dots as indicators:</strong></p>
<ol>
<li>It shall always show a full image, no in between - hence if the user drags and stops in the middle, it shall automatically jump to the full image.</li>
<li>I want dots as indicators. </li>
</ol>
<p>Since I've seen a lot of apps use such a slider, there must be known method, right? </p> | 58,904,512 | 2 | 1 | null | 2019-11-17 01:13:52.543 UTC | 9 | 2021-09-25 21:15:20.87 UTC | 2019-11-17 01:17:07.49 UTC | null | 1,226,963 | null | 11,397,070 | null | 1 | 24 | swift|swiftui | 13,303 | <p>There is no built-in method for this in SwiftUI this year. I'm sure a system-standard implementation will come along in the future.</p>
<p>In the short term, you have two options. As Asperi noted, Apple's own tutorials have a section on wrapping the PageViewController from UIKit for use in SwiftUI (see <a href="https://developer.apple.com/tutorials/swiftui/interfacing-with-uikit" rel="noreferrer">Interfacing with UIKit</a>).</p>
<p>The second option is to roll your own. It's entirely possible to make something similar in SwiftUI. Here's a proof of concept, where the index can be changed by swipe or by binding:</p>
<pre><code>struct PagingView<Content>: View where Content: View {
@Binding var index: Int
let maxIndex: Int
let content: () -> Content
@State private var offset = CGFloat.zero
@State private var dragging = false
init(index: Binding<Int>, maxIndex: Int, @ViewBuilder content: @escaping () -> Content) {
self._index = index
self.maxIndex = maxIndex
self.content = content
}
var body: some View {
ZStack(alignment: .bottomTrailing) {
GeometryReader { geometry in
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 0) {
self.content()
.frame(width: geometry.size.width, height: geometry.size.height)
.clipped()
}
}
.content.offset(x: self.offset(in: geometry), y: 0)
.frame(width: geometry.size.width, alignment: .leading)
.gesture(
DragGesture().onChanged { value in
self.dragging = true
self.offset = -CGFloat(self.index) * geometry.size.width + value.translation.width
}
.onEnded { value in
let predictedEndOffset = -CGFloat(self.index) * geometry.size.width + value.predictedEndTranslation.width
let predictedIndex = Int(round(predictedEndOffset / -geometry.size.width))
self.index = self.clampedIndex(from: predictedIndex)
withAnimation(.easeOut) {
self.dragging = false
}
}
)
}
.clipped()
PageControl(index: $index, maxIndex: maxIndex)
}
}
func offset(in geometry: GeometryProxy) -> CGFloat {
if self.dragging {
return max(min(self.offset, 0), -CGFloat(self.maxIndex) * geometry.size.width)
} else {
return -CGFloat(self.index) * geometry.size.width
}
}
func clampedIndex(from predictedIndex: Int) -> Int {
let newIndex = min(max(predictedIndex, self.index - 1), self.index + 1)
guard newIndex >= 0 else { return 0 }
guard newIndex <= maxIndex else { return maxIndex }
return newIndex
}
}
struct PageControl: View {
@Binding var index: Int
let maxIndex: Int
var body: some View {
HStack(spacing: 8) {
ForEach(0...maxIndex, id: \.self) { index in
Circle()
.fill(index == self.index ? Color.white : Color.gray)
.frame(width: 8, height: 8)
}
}
.padding(15)
}
}
</code></pre>
<p>and a demo</p>
<pre><code>struct ContentView: View {
@State var index = 0
var images = ["10-12", "10-13", "10-14", "10-15"]
var body: some View {
VStack(spacing: 20) {
PagingView(index: $index.animation(), maxIndex: images.count - 1) {
ForEach(self.images, id: \.self) { imageName in
Image(imageName)
.resizable()
.scaledToFill()
}
}
.aspectRatio(4/3, contentMode: .fit)
.clipShape(RoundedRectangle(cornerRadius: 15))
PagingView(index: $index.animation(), maxIndex: images.count - 1) {
ForEach(self.images, id: \.self) { imageName in
Image(imageName)
.resizable()
.scaledToFill()
}
}
.aspectRatio(3/4, contentMode: .fit)
.clipShape(RoundedRectangle(cornerRadius: 15))
Stepper("Index: \(index)", value: $index.animation(.easeInOut), in: 0...images.count-1)
.font(Font.body.monospacedDigit())
}
.padding()
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/fvXNJ.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/fvXNJ.gif" alt="PagingView demo"></a></p>
<p>Two notes:</p>
<ol>
<li>The GIF animation does a really poor job of showing how smooth the animation is, as I had to drop the framerate and compress heavily due to file size limits. It looks great on simulator or a real device</li>
<li>The drag gesture in the simulator feels clunky, but it works really well on a physical device.</li>
</ol> |
749,968 | Learning Oracle for the first time | <p>I am a very experienced MS Sql developer, and a few new job positions are coming my way where I will be working with Oracle on a more daily basis.</p>
<p>As with all the technologies I have learned, I want to know the best places and books to get started and up to speed with designing and developing with Oracle, but with pure C#.</p>
<p>What resources are there for us Microsoft guys to jump in and go with Oracle? I realize there is oracle.com and asktom.oracle.com, as well as the mass amount of documentation on Oracle, I am looking more for a quick primer (setting up a server, getting some sample data to play with, etc...) rather than in depth sql vs. oracle technology comparisons.</p>
<p>Thanks in advance.</p> | 749,989 | 4 | 0 | null | 2009-04-15 01:29:29.517 UTC | 10 | 2009-05-12 07:04:02.367 UTC | 2009-05-12 07:04:02.367 UTC | null | 50,552 | null | 13,502 | null | 1 | 8 | c#|.net|sql-server|oracle | 895 | <p><a href="http://www.oracle.com/technology/tech/dotnet/tools/index.html" rel="nofollow noreferrer">Oracle Developer Tools for Visual Studio</a></p>
<p><a href="http://www.oracle.com/technology/tech/dotnet/pdf/ODT11_whatsnew.pdf" rel="nofollow noreferrer">White Paper: New 11g Features in Oracle Developer Tools (PDF)</a> </p>
<p><a href="http://www.oracle.com/technologies/microsoft/docs/idc-interop.pdf" rel="nofollow noreferrer">Oracle Database with Windows and .NET</a></p>
<p><a href="http://www.oracle.com/technology/obe/hol08/dotnet/asp/asp_otn.htm" rel="nofollow noreferrer">Oracle by Example: Building ASP.NET Web Applications with ODT</a></p>
<p><a href="http://www.oracle.com/technology/obe/hol08/dotnet/buildnet/buildnet_otn.htm" rel="nofollow noreferrer">Oracle by Example: Building .NET Applications Using ODT</a> </p>
<p><a href="http://www.oracle.com/technology/obe/hol08/dotnet/debugging/debugging_otn.htm" rel="nofollow noreferrer">Oracle by Example: Debugging Oracle PL/SQL from Visual Studio</a> </p>
<p><a href="http://www.oracle.com/technology/obe/hol08/dotnet/udt/udt_otn.htm" rel="nofollow noreferrer">Oracle by Example: Using Oracle User-Defined Types with .NET and Visual Studio</a> </p>
<p><a href="http://www.oracle.com/technology/oramag/oracle/08-may/o38net.html" rel="nofollow noreferrer">Oracle Magazine: Build Applications with ODT and Oracle User-Defined Types</a></p>
<p><a href="http://www.oracle.com/technology/tech/dotnet/col/odt_faq.html" rel="nofollow noreferrer">ODT FAQ: Answers to Common OTN Discussion Forum Questions</a> </p> |
611,459 | How to sort text in sqlite3 with specified locale? | <p>Sqlite3 by default sorts only by ascii letters. I tried to look in google, but the only thing I found were informations about collations. Sqlite3 has only <code>NOCASE</code>, <code>RTRIM</code> and <code>BIARY</code> collations. How to add support for a specific locale?
(I'm using it in Rails application)</p> | 614,609 | 4 | 0 | null | 2009-03-04 16:50:51.057 UTC | 13 | 2019-11-17 15:21:03.12 UTC | 2016-11-06 19:44:41.51 UTC | null | 178,163 | klew | 58,877 | null | 1 | 16 | ruby-on-rails|sqlite|locale|collation | 16,658 | <p>SQLite <a href="http://www.sqlite.org/src/doc/trunk/ext/icu/README.txt" rel="nofollow noreferrer">supports</a> integration with <a href="http://icu-project.org/" rel="nofollow noreferrer">ICU</a>. According to the Readme file,
<code>sqlite/ext/icu/README.txt</code>
the <code>sqlite/ext/icu/</code> directory contains source code for the SQLite "ICU" extension, an
integration of the "International Components for Unicode" library with SQLite. </p>
<pre><code>1. Features
1.1 SQL Scalars upper() and lower()
1.2 Unicode Aware LIKE Operator
1.3 ICU Collation Sequences
1.4 SQL REGEXP Operator
</code></pre> |
1,196,467 | OK to put comments before the XML declaration? | <p>Is it OK to put comments before the XML declaration in an XML file?</p>
<pre><code><!--
Is this bad to do?
-->
<?xml version="1.0" encoding="utf-8"?>
<someElement />
</code></pre> | 1,196,485 | 4 | 4 | null | 2009-07-28 20:13:16.373 UTC | 3 | 2021-06-06 04:58:45.327 UTC | null | null | null | null | 111,327 | null | 1 | 32 | xml|xml-declaration | 4,945 | <p>No, it's not OK.</p>
<p><a href="http://www.w3.org/TR/2008/REC-xml-20081126/#sec-guessing" rel="noreferrer">Appendix F of the XML spec</a> says:</p>
<blockquote>
<p>Because each XML entity not
accompanied by external encoding
information and not in UTF-8 or UTF-16
encoding must begin with an XML
encoding declaration, in which the
first characters must be '< ?xml', any
conforming processor can detect, after
two to four octets of input, which of
the following cases apply.</p>
</blockquote>
<p>Ah, but, section F is non-normative, you say.</p>
<p>Well, <a href="http://www.w3.org/TR/2008/REC-xml-20081126/#sec-well-formed" rel="noreferrer">section 2.1</a> gives the production for a well-formed XML document, thus:</p>
<pre><code>[1] document ::= prolog element Misc*
</code></pre>
<p>...and in <a href="http://www.w3.org/TR/2008/REC-xml-20081126/#sec-prolog-dtd" rel="noreferrer">section 2.8</a> we get the production for "prolog":</p>
<pre><code>[22] prolog ::= XMLDecl? Misc* (doctypedecl Misc*)?
[23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
</code></pre>
<p>So, you can <em>omit</em> the < ?xml declaration, but you can't prefix it with anything.</p>
<p>(Incidentally, "Misc" is the category that comments fall into).</p> |
51,810,420 | Flutter - InputDecoration border only when focused | <p>I am trying to Design a custom <code>TextFormField</code> and everything is working fine except that I only need to show a border when the <code>TextFormField</code> is focused (someone has tapped into it).</p>
<p>As I don't think that is possible I tried to change the color of the border, but it seems to me that this color can only be set through the <code>hintColor</code> of the theme. But as the <code>hintColor</code> also changes the color of the hint Text being displayed i can't use that.</p>
<pre><code>final theme = Theme.of(context);
return new Theme(
data: theme.copyWith(primaryColor: Colors.blue),
child: TextFormField(
autocorrect: false,
style: TextStyle(color: Colors.green),
decoration: new InputDecoration(
fillColor: Colors.white,
filled: true,
contentPadding:
EdgeInsets.only(bottom: 10.0, left: 10.0, right: 10.0),
labelText: title,
),
validator: this.validator,
onSaved: (String newValue) {
setMethod(newValue);
},
),
);
</code></pre>
<p>Does anyone have an idea how to solve this problem?</p> | 51,810,972 | 1 | 0 | null | 2018-08-12 15:51:38.253 UTC | 6 | 2018-08-12 17:57:11.76 UTC | null | null | null | null | 6,389,452 | null | 1 | 12 | dart|flutter|flutter-layout | 48,901 | <p>There is a property named <code>focusedBorder</code>, you can use and change it according to your needs, and also set the default border as <code>InputBorder.none</code>, example:</p>
<pre><code> @override
Widget build(BuildContext context) {
return TextFormField(
autocorrect: false,
focusNode: _focusNode,
style: TextStyle(color: Colors.green),
decoration: new InputDecoration(
fillColor: Colors.white,
border: InputBorder.none,
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
borderSide: BorderSide(color: Colors.blue)),
filled: true,
contentPadding:
EdgeInsets.only(bottom: 10.0, left: 10.0, right: 10.0),
labelText: widget.title,
),
validator: widget.validator,
onSaved: (String newValue) {},
);
}
</code></pre>
<p><strong>Update if you don't have the focusedBorder attribute</strong></p>
<pre><code> class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: <Widget>[
MyCustomTextField(
title: "Testing 1",
),
MyCustomTextField(
title: "Testing 2",
)
],
));
}
}
class MyCustomTextField extends StatefulWidget {
final String title;
final ValueChanged<String> validator;
MyCustomTextField({this.title, this.validator});
@override
_MyCustomTextFieldState createState() => _MyCustomTextFieldState();
}
class _MyCustomTextFieldState extends State<MyCustomTextField> {
var _focusNode = new FocusNode();
_focusListener() {
setState(() {});
}
@override
void initState() {
_focusNode.addListener(_focusListener);
super.initState();
}
@override
void dispose() {
_focusNode.removeListener(_focusListener);
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextFormField(
autocorrect: false,
focusNode: _focusNode,
style: TextStyle(color: Colors.green),
decoration: new InputDecoration(
fillColor: Colors.white,
border: _focusNode.hasFocus
? OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
borderSide: BorderSide(color: Colors.blue))
: InputBorder.none,
filled: true,
contentPadding: EdgeInsets.only(bottom: 10.0, left: 10.0, right: 10.0),
labelText: widget.title,
),
validator: widget.validator,
onSaved: (String newValue) {},
);
}
}
</code></pre> |
51,680,709 | Colored text output in PowerShell console using ANSI / VT100 codes | <p>I wrote a program which prints a string, which contains <a href="https://blogs.msdn.microsoft.com/commandline/2017/10/11/whats-new-in-windows-console-in-windows-10-fall-creators-update/" rel="noreferrer">ANSI escape sequences</a> to make the text colored. But it doesn't work as expected in the default Windows 10 console, as you can see in the screenshot.</p>
<p>The program output appears with the escape sequences as printed characters.
If I feed that string to PowerShell via a variable or piping, the output appears as intended (red text).</p>
<p>How can I achieve that the program prints colored text without any workarounds?</p>
<p><a href="https://i.stack.imgur.com/VOUk0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VOUk0.png" alt="enter image description here"></a></p>
<p>This is my program source (Haskell) - but the language is not relevant, just so you can see how the escape sequences are written.</p>
<pre><code>main = do
let red = "\ESC[31m"
let reset = "\ESC[39m"
putStrLn $ red ++ "RED" ++ reset
</code></pre> | 51,681,675 | 3 | 0 | null | 2018-08-03 22:19:35.15 UTC | 20 | 2022-09-20 03:26:33.623 UTC | 2018-08-03 23:13:30.293 UTC | null | 5,329,137 | user2226112 | null | null | 1 | 41 | powershell|ansi|windows-console|vt100 | 23,625 | <p>Note:</p>
<ul>
<li><p>The following applies to <em>regular</em> (legacy) console windows on Windows (provided by <code>conhost.exe</code>), which are used <em>by default</em>, including when a console application is launched from a GUI application.</p>
</li>
<li><p>By contrast, the console windows (terminals) provided by <a href="https://aka.ms/windowsterminal" rel="nofollow noreferrer">Windows Terminal</a> provide support for VT / ANSI escape sequences <em>by default</em>, for <em>all</em> console applications.</p>
</li>
</ul>
<hr />
<p>While <strong>console windows in Windows 10 do support VT (Virtual Terminal) / ANSI escape sequences</strong> <em>in principle</em>, <strong>support is turned <em>OFF by default</em></strong>.</p>
<p>You have three options:</p>
<ul>
<li><p>(a) <strong>Activate support <em>globally by default, persistently</em></strong>, via the registry, as detailed in <a href="https://superuser.com/a/1300251/139307">this SU answer</a>.</p>
<ul>
<li>In short: In registry key <code>[HKEY_CURRENT_USER\Console]</code>, create or set the <code>VirtualTerminalLevel</code> DWORD value to <code>1</code>
<ul>
<li>From PowerShell, you can do this <em>programmatically</em> as follows:<br />
<code>Set-ItemProperty HKCU:\Console VirtualTerminalLevel -Type DWORD 1</code></li>
<li>From <code>cmd.exe</code> (also works from PowerShell):<br />
<code>reg add HKCU\Console /v VirtualTerminalLevel /t REG_DWORD /d 1</code></li>
</ul>
</li>
<li>Open a new console window for changes to take effect.</li>
<li>See caveats below.</li>
</ul>
</li>
<li><p>(b) <strong>Activate support <em>from inside your program, for that program (process) only</em></strong>, with a call to the <code>SetConsoleMode()</code> Windows API function.</p>
<ul>
<li>See details below.</li>
</ul>
</li>
<li><p>(c) <strong>Ad-hoc workaround, <em>from PowerShell</em></strong>: pipe output from external programs to <code>Out-Host</code>; e.g., <code>.\test.exe | Out-Host</code></p>
<ul>
<li>See details below.</li>
</ul>
</li>
</ul>
<hr />
<h3>Re (a):</h3>
<p>The registry-based approach <strong>invariably activates VT support <em>globally</em>, i.e., for <em>all</em> console windows</strong>, irrespective of what shell / program runs in them:</p>
<ul>
<li><p>Individual executables / shells can still deactivate support for themselves, if desired, using method (b).</p>
</li>
<li><p>Conversely, however, this means that the output of any program that doesn't explicitly control VT support will be subject to interpretation of VT sequences; while this is generally desirable, hypothetically this could lead to misinterpretation of output from programs that <em>accidentally</em> produce output with VT-like sequences.</p>
</li>
</ul>
<p>Note:</p>
<ul>
<li><p>While there <em>is</em> a mechanism that allows console-window settings to be scoped by startup executable / window title, via <em>subkeys</em> of <code>[HKEY_CURRENT_USR\Console]</code>, the <code>VirtualTerminalLevel</code> value seems not to be supported there.</p>
</li>
<li><p>Even if it were, however, it wouldn't be a <em>robust</em> solution, because opening a console window via a <em>shortcut</em> file (<code>*.lnk</code>) (e.g. from the Start Menu or Task Bar) wouldn't respect these settings, because <code>*.lnk</code> files have settings <em>built into them</em>; while you can modify these built-in settings via the <code>Properties</code> GUI dialog, as of this writing the <code>VirtualTerminalLevel</code> setting is not surfaced in that GUI.</p>
</li>
</ul>
<hr />
<h3>Re (b):</h3>
<p>Calling the <a href="https://docs.microsoft.com/en-us/windows/console/setconsolemode" rel="nofollow noreferrer"><code>SetConsoleMode()</code></a> Windows API function <em>from inside the program (process)</em>, as shown <a href="https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#example-of-enabling-virtual-terminal-processing" rel="nofollow noreferrer">here</a>, is cumbersome even in C# (due to requiring P/Invoke declarations), and <strong>may not be an option</strong>:</p>
<ul>
<li><p>for programs written in languages from which calling the Windows API is not supported.</p>
</li>
<li><p>if you have a preexisting executable that you cannot modify.</p>
</li>
</ul>
<p>In that event, option (c) (from PowerShell), discussed next, may work for you.</p>
<hr />
<h3>Re (c):</h3>
<p><strong>PowerShell automatically activates VT (virtual terminal) support <em>for itself</em></strong> when it starts (in recent releases of Windows 10 this applies to both Windows PowerShell and PowerShell (Core) 7+) - but that <strong>does <em>not</em> extend to external programs <em>called from</em> Windows PowerShell</strong> (but <em>does</em> when called from PowerShell (Core) as of at least 7.2.2).</p>
<p>However, <strong>if you <em>relay</em> an external program's output via PowerShell, VT sequences <em>are</em> recognized</strong>; using <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/out-host" rel="nofollow noreferrer"><code>Out-Host</code></a> is the simplest way to do that (<code>Write-Host</code> would work too):</p>
<pre><code>.\test.exe | Out-Host
</code></pre>
<p>Note: Use <code>Out-Host</code> only if you mean to print to the <em>console</em>; if, by contrast, you want to <em>capture</em> the external program's output, use just <code>$capturedOutput = .\test.exe</code></p>
<p>Alternatively, you can <strong>enclose the call in <code>(...)</code></strong>, which, however, <em>invariably collects all output first</em>, before relaying it.</p>
<pre><code>(.\test.exe)
</code></pre>
<p><strong>Character-encoding caveat</strong>: Windows PowerShell by default expects output from external programs to use the OEM code page, as defined by the legacy system locale (e.g., <code>437</code> on US-English systems) and as reflected in <code>[console]::OutputEncoding</code>.
.NET console programs respect that setting automatically, but for non-.NET programs (e.g., Python scripts) that use a different encoding (and produce not just pure ASCII output (in the 7-bit range)), you must (at least temporarily) specify that encoding by assigning to <code>[console]::OutputEncoding</code>; e.g., for UTF-8:<br />
<code>[console]::OutputEncoding = [Text.Encoding]::Utf8</code>.<br />
Note that this is not only necessary for the VT-sequences workaround, but <strong>generally necessary for PowerShell to interpret non-ASCII characters correctly</strong>.</p>
<p>PowerShell <em>Core</em> (v6+), unfortunately, as of v7.2, still defaults to the OEM code page too, but that <a href="https://github.com/PowerShell/PowerShell/issues/7233" rel="nofollow noreferrer">should be considered a <em>bug</em></a>, given that it otherwise defaults to <em>UTF-8 without BOM</em>.</p> |
577,724 | Trouble playing wav in Java | <p>I'm trying to play a</p>
<pre><code>PCM_UNSIGNED 11025.0 Hz, 8 bit, mono, 1 bytes/frame
</code></pre>
<p>file as described <a href="https://stackoverflow.com/questions/26305/how-can-i-play-sound-in-java/26311#26311">here (1)</a> and <a href="https://stackoverflow.com/questions/26305/how-can-i-play-sound-in-java/26318#26318">here(2)</a>.</p>
<p>The first approach works, but I don't want to depend on <code>sun.*</code> stuff. The second results in just some leading frames being played, that sounds more like a click. Can't be an IO issue as I'm playing from a ByteArrayInputStream.</p>
<p>Plz share your ideas on why might this happen. TIA.</p> | 577,926 | 1 | 0 | null | 2009-02-23 14:02:07.947 UTC | 9 | 2012-09-27 22:58:08.093 UTC | 2017-05-23 11:58:58.747 UTC | starblue | -1 | gsmd | 15,187 | null | 1 | 9 | java|wav|playback|javasound | 21,170 | <p>I'm not sure why the second approach you linked to starts another thread; I believe the audio will be played in its own thread anyway. Is the problem that your application finishes before the clip has finished playing?</p>
<pre><code>import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.LineEvent.Type;
private static void playClip(File clipFile) throws IOException,
UnsupportedAudioFileException, LineUnavailableException, InterruptedException {
class AudioListener implements LineListener {
private boolean done = false;
@Override public synchronized void update(LineEvent event) {
Type eventType = event.getType();
if (eventType == Type.STOP || eventType == Type.CLOSE) {
done = true;
notifyAll();
}
}
public synchronized void waitUntilDone() throws InterruptedException {
while (!done) { wait(); }
}
}
AudioListener listener = new AudioListener();
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(clipFile);
try {
Clip clip = AudioSystem.getClip();
clip.addLineListener(listener);
clip.open(audioInputStream);
try {
clip.start();
listener.waitUntilDone();
} finally {
clip.close();
}
} finally {
audioInputStream.close();
}
}
</code></pre> |
42,209,875 | Hive 2.1.1 MetaException(message:Version information not found in metastore. ) | <p>I'm running Hadoop 2.7.3, MySQL 5.7.17 and Hive 2.1.1 on Ubuntu 16.04.</p>
<p>When I run ./hive, I keep getting the following warning and exception:</p>
<pre><code>SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/home/server/hive/lib/log4j-slf4j-impl-2.4.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/home/server/hadoop/share/hadoop/common/lib/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]
Logging initialized using configuration in jar:file:/home/server/hive/lib/hive-common-2.1.1.jar!/hive-log4j2.properties Async: true
Mon Feb 13 12:01:41 EST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Feb 13 12:01:41 EST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Feb 13 12:01:41 EST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Feb 13 12:01:41 EST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Feb 13 12:01:42 EST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Feb 13 12:01:42 EST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Feb 13 12:01:42 EST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Feb 13 12:01:42 EST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Exception in thread "main" java.lang.RuntimeException: org.apache.hadoop.hive.ql.metadata.HiveException: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient
at org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:591)
at org.apache.hadoop.hive.ql.session.SessionState.beginStart(SessionState.java:531)
at org.apache.hadoop.hive.cli.CliDriver.run(CliDriver.java:705)
at org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:641)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
Caused by: org.apache.hadoop.hive.ql.metadata.HiveException: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient
at org.apache.hadoop.hive.ql.metadata.Hive.registerAllFunctionsOnce(Hive.java:226)
at org.apache.hadoop.hive.ql.metadata.Hive.<init>(Hive.java:366)
at org.apache.hadoop.hive.ql.metadata.Hive.create(Hive.java:310)
at org.apache.hadoop.hive.ql.metadata.Hive.getInternal(Hive.java:290)
at org.apache.hadoop.hive.ql.metadata.Hive.get(Hive.java:266)
at org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:558)
... 9 more
Caused by: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient
at org.apache.hadoop.hive.metastore.MetaStoreUtils.newInstance(MetaStoreUtils.java:1654)
at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.<init>(RetryingMetaStoreClient.java:80)
at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.getProxy(RetryingMetaStoreClient.java:130)
at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.getProxy(RetryingMetaStoreClient.java:101)
at org.apache.hadoop.hive.ql.metadata.Hive.createMetaStoreClient(Hive.java:3367)
at org.apache.hadoop.hive.ql.metadata.Hive.getMSC(Hive.java:3406)
at org.apache.hadoop.hive.ql.metadata.Hive.getMSC(Hive.java:3386)
at org.apache.hadoop.hive.ql.metadata.Hive.getAllFunctions(Hive.java:3640)
at org.apache.hadoop.hive.ql.metadata.Hive.reloadFunctions(Hive.java:236)
at org.apache.hadoop.hive.ql.metadata.Hive.registerAllFunctionsOnce(Hive.java:221)
... 14 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.apache.hadoop.hive.metastore.MetaStoreUtils.newInstance(MetaStoreUtils.java:1652)
... 23 more
Caused by: MetaException(message:Version information not found in metastore. )
at org.apache.hadoop.hive.metastore.ObjectStore.checkSchema(ObjectStore.java:7753)
at org.apache.hadoop.hive.metastore.ObjectStore.verifySchema(ObjectStore.java:7731)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.hadoop.hive.metastore.RawStoreProxy.invoke(RawStoreProxy.java:101)
at com.sun.proxy.$Proxy21.verifySchema(Unknown Source)
at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.getMS(HiveMetaStore.java:565)
at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.createDefaultDB(HiveMetaStore.java:626)
at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.init(HiveMetaStore.java:416)
at org.apache.hadoop.hive.metastore.RetryingHMSHandler.<init>(RetryingHMSHandler.java:78)
at org.apache.hadoop.hive.metastore.RetryingHMSHandler.getProxy(RetryingHMSHandler.java:84)
at org.apache.hadoop.hive.metastore.HiveMetaStore.newRetryingHMSHandler(HiveMetaStore.java:6490)
at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.<init>(HiveMetaStoreClient.java:238)
at org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient.<init>(SessionHiveMetaStoreClient.java:70)
... 28 more
</code></pre>
<p>Here is my hive-site.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
<property>
<name>javax.jdo.option.ConnectionURL</name>
<value>jdbc:mysql://localhost:3306/hive?createDatabaseIfNotExist=true</value>
</property>
<property>
<name>javax.jdo.option.ConnectionDriverName</name>
<value>com.mysql.jdbc.Driver</value>
</property>
<property>
<name>javax.jdo.option.ConnectionUserName</name>
<value>hive</value>
</property>
<property>
<name>javax.jdo.option.ConnectionPassword</name>
<value>password</value>
</property>
</configuration>
</code></pre>
<p>In order to fix the error, I've tried <a href="https://stackoverflow.com/questions/41939582/hive-unable-to-instantiate-org-apache-hadoop-hive-ql-metadata-sessionhivemetasto">Hive Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient</a> and <a href="https://stackoverflow.com/questions/35449274/java-lang-runtimeexception-unable-to-instantiate-org-apache-hadoop-hive-ql-meta">Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient</a>. But I am still getting the same exceptions.</p>
<p>I'm newbie to Hadoop and Hive, how could I fix the exception?
Thanks!</p> | 42,210,184 | 6 | 0 | null | 2017-02-13 17:22:39.737 UTC | 9 | 2022-01-17 16:38:06.38 UTC | 2020-04-15 04:16:40.06 UTC | null | 7,303,447 | null | 7,506,662 | null | 1 | 19 | mysql|hadoop|hive | 29,728 | <p>The necessary tables required for the metastore are missing in MySQL. Manually create the tables and restart hive metastore. </p>
<p>The schema files for MySQL will be available under the path <code>$HIVE_HOME/scripts/metastore/upgrade/mysql/</code>.</p>
<pre><code>cd $HIVE_HOME/scripts/metastore/upgrade/mysql/
< Login into MySQL >
mysql> drop database IF EXISTS hive;
mysql> create database hive;
mysql> use hive;
mysql> source hive-schema-2.1.1.mysql.sql;
</code></pre>
<p>Restart Hive metastore.</p> |
29,889,495 | Count specific string in text file using PowerShell | <p>Is it possible to count specific strings in a file and save the value in a variable?</p>
<p>For me it would be the String "/export" (without quotes).</p> | 29,889,664 | 4 | 0 | null | 2015-04-27 07:17:35.313 UTC | 2 | 2021-09-05 21:30:56.683 UTC | 2018-12-06 23:13:22.723 UTC | null | 63,550 | null | 3,322,838 | null | 1 | 24 | powershell | 65,940 | <p>Here's one method:</p>
<pre><code>$FileContent = Get-Content "YourFile.txt"
$Matches = Select-String -InputObject $FileContent -Pattern "/export" -AllMatches
$Matches.Matches.Count
</code></pre> |
29,999,024 | Adding Thousand Separator to Int in Swift | <p>I am fairly new to Swift and having a great deal of trouble finding a way to add a space as a thousand separator. </p>
<p>What I am hoping to achieve is taking the result of a calculation and displaying it in a textfield so that the format is:</p>
<blockquote>
<p>2 358 000</p>
</blockquote>
<p>instead of</p>
<blockquote>
<p>2358000</p>
</blockquote>
<p>for example. </p>
<p>I am not sure if I should be formatting the Int value and then converting it to a String, or adding the space after the Int value is converted to a String. Any help would be greatly appreciated.</p> | 29,999,137 | 7 | 0 | null | 2015-05-02 05:59:57.263 UTC | 11 | 2020-05-26 16:19:48.463 UTC | 2015-05-08 15:05:33.217 UTC | null | 716,216 | null | 4,718,413 | null | 1 | 73 | ios|swift|separator | 52,674 | <p>You can use NSNumberFormatter to specify a different grouping separator as follow:</p>
<p>update: <strong>Xcode 11.5 • Swift 5.2</strong></p>
<pre><code>extension Formatter {
static let withSeparator: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.groupingSeparator = " "
return formatter
}()
}
</code></pre>
<hr>
<pre><code>extension Numeric {
var formattedWithSeparator: String { Formatter.withSeparator.string(for: self) ?? "" }
}
</code></pre>
<hr>
<pre><code>2358000.formattedWithSeparator // "2 358 000"
2358000.99.formattedWithSeparator // "2 358 000.99"
let int = 2358000
let intFormatted = int.formattedWithSeparator // "2 358 000"
let decimal: Decimal = 2358000
let decimalFormatted = decimal.formattedWithSeparator // "2 358 000"
let decimalWithFractionalDigits: Decimal = 2358000.99
let decimalWithFractionalDigitsFormatted = decimalWithFractionalDigits.formattedWithSeparator // "2 358 000.99"
</code></pre>
<hr>
<p>If you need to display your value as currency with current locale or with a fixed locale:</p>
<pre><code>extension Formatter {
static let number = NumberFormatter()
}
extension Locale {
static let englishUS: Locale = .init(identifier: "en_US")
static let frenchFR: Locale = .init(identifier: "fr_FR")
static let portugueseBR: Locale = .init(identifier: "pt_BR")
// ... and so on
}
extension Numeric {
func formatted(with groupingSeparator: String? = nil, style: NumberFormatter.Style, locale: Locale = .current) -> String {
Formatter.number.locale = locale
Formatter.number.numberStyle = style
if let groupingSeparator = groupingSeparator {
Formatter.number.groupingSeparator = groupingSeparator
}
return Formatter.number.string(for: self) ?? ""
}
// Localized
var currency: String { formatted(style: .currency) }
// Fixed locales
var currencyUS: String { formatted(style: .currency, locale: .englishUS) }
var currencyFR: String { formatted(style: .currency, locale: .frenchFR) }
var currencyBR: String { formatted(style: .currency, locale: .portugueseBR) }
// ... and so on
var calculator: String { formatted(groupingSeparator: " ", style: .decimal) }
}
</code></pre>
<hr>
<p>Usage:</p>
<pre><code>1234.99.currency // "$1,234.99"
1234.99.currencyUS // "$1,234.99"
1234.99.currencyFR // "1 234,99 €"
1234.99.currencyBR // "R$ 1.234,99"
1234.99.calculator // "1 234.99"
</code></pre>
<p>Note: If you would like to have a space with the same width of a period you can use <code>"\u{2008}"</code> </p>
<p><a href="https://www.cs.tut.fi/~jkorpela/chars/spaces.html" rel="noreferrer">unicode spaces</a></p>
<pre><code>formatter.groupingSeparator = "\u{2008}"
</code></pre> |
35,257,287 | Kestrel shutdown function in Startup.cs in ASP.NET Core | <p>Is there a shutdown function when using <code>Microsoft.AspNet.Server.Kestrel</code>? <code>ASP.NET Core</code> (formerly <code>ASP.NET vNext</code>) clearly has a Startup sequence, but no mention of shutdown sequence and how to handle clean closure.</p> | 35,257,670 | 5 | 0 | null | 2016-02-07 18:23:47.12 UTC | 7 | 2022-07-11 09:39:41.11 UTC | 2019-12-10 10:09:31.993 UTC | null | 9,020,340 | null | 237,315 | null | 1 | 44 | c#|asp.net-core | 22,145 | <p>In ASP.NET Core you can register to the cancellation tokens provided by <code>IApplicationLifetime</code></p>
<pre class="lang-cs prettyprint-override"><code>public class Startup
{
public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime)
{
applicationLifetime.ApplicationStopping.Register(OnShutdown);
}
private void OnShutdown()
{
// Do your cleanup here
}
}
</code></pre>
<p><code>IApplicationLifetime</code> is also exposing cancellation tokens for <code>ApplicationStopped</code> and <code>ApplicationStarted</code> as well as a <code>StopApplication()</code> method to stop the application.</p>
<h3>For .NET Core 3.0+</h3>
<p>From comments <a href="https://stackoverflow.com/users/6747751/horkrine">@Horkrine</a></p>
<blockquote>
<p>For .NET Core 3.0+ it is recommended to use IHostApplicationLifetime instead, as IApplicationLifetime will be deprecated soon. The rest will still work as written above with the new service</p>
</blockquote> |
18,139,710 | Using c++11 in MacOS X and compiled Boost libraries conundrum | <p>I am trying to compile a c++ project that uses c++11 standards extensively. Everything was going well with just -std=c++11, until I tried to use unordered_map and MacOS simply doesn't have the unordered_map header file anywhere in usr/include. </p>
<p>I did some research and found that using -stdlib=libc++ would fix it (not sure how, this seems like magic to me if the include file is nowhere in the filesystem). It certainly did. It compiled well, but the linker cannot link to the boost::program_options that my program also uses extensively. Without -stdlib=libc++, boost links perfectly, but I lose the unordered_map.</p>
<p>What should I do to have the latest C++11 features with the Mac OS clang++ compiler and still be able to link to boost libraries (which were built from sources on this very mac)</p>
<p>ps: all works fine in my arch linux box</p>
<p>my makefile: </p>
<blockquote>
<p>LIBS = -lboost_program_options CXXFLAGS = -stdlib=libc++ -std=c++11
-Wall -g OBJ = fastq.o fastq_reader.o main.o degenerate.o interleave.o complement.o interval_utils.o interval.o interval_utils_test_tool.o</p>
<p>foghorn: $(OBJ) $(LINK.cc) -o $@ $^ $(LIBS)</p>
</blockquote>
<p>The output using -stdlib=libc++</p>
<blockquote>
<p>$ make c++ -stdlib=libc++ -std=c++11 -Wall -g -c -o fastq.o
fastq.cpp c++ -stdlib=libc++ -std=c++11 -Wall -g -c -o
fastq_reader.o fastq_reader.cpp c++ -stdlib=libc++ -std=c++11 -Wall -g
-c -o main.o main.cpp c++ -stdlib=libc++ -std=c++11 -Wall -g -c -o degenerate.o degenerate.cpp c++ -stdlib=libc++ -std=c++11 -Wall -g<br>
-c -o interleave.o interleave.cpp c++ -stdlib=libc++ -std=c++11 -Wall -g -c -o complement.o complement.cpp c++ -stdlib=libc++ -std=c++11 -Wall -g -c -o interval_utils.o interval_utils.cpp c++ -stdlib=libc++ -std=c++11 -Wall -g -c -o interval.o interval.cpp c++ -stdlib=libc++ -std=c++11 -Wall -g -c -o interval_utils_test_tool.o interval_utils_test_tool.cpp c++ -stdlib=libc++ -std=c++11 -Wall -g<br>
-o foghorn fastq.o fastq_reader.o main.o degenerate.o interleave.o complement.o interval_utils.o interval.o interval_utils_test_tool.o
-lboost_program_options Undefined symbols for architecture x86_64: "boost::program_options::to_internal(std::__1::basic_string, std::__1::allocator > const&)",
referenced from:
std::__1::vector, std::__1::allocator >,
std::__1::allocator, std::__1::allocator > > >
boost::program_options::to_internal, std::__1::allocator ></p>
<blockquote>
<p>(std::__1::vector, std::__1::allocator >,
std::__1::allocator, std::__1::allocator > > > const&)
in main.o</p>
</blockquote>
<pre><code> ... [clipped output for readability]
</code></pre>
<p>ld: symbol(s) not found for architecture x86_64 clang: error: linker
command failed with exit code 1 (use -v to see invocation) make: <em>*</em>
[foghorn] Error 1</p>
</blockquote> | 18,139,954 | 1 | 3 | null | 2013-08-09 03:39:05.007 UTC | 9 | 2019-08-12 05:14:00.843 UTC | 2013-11-21 19:44:18.853 UTC | null | 309,425 | null | 1,139,854 | null | 1 | 15 | c++|macos|boost|c++11 | 13,842 | <blockquote>
<p>edit: See comments below for modern MacOS; the --c++11 flag is no longer valid</p>
</blockquote>
<p>After a lot of research, I learned the following:</p>
<ul>
<li>Everything on MacOS X is built using stdlibc++ (including everything you install with homebrew -- which was my case)</li>
<li>stdlibc++ that comes with gcc 4.2 does not implement many of the features of c++11. Examples are unordered_map, to_string, stoi, ... only libc++ does.</li>
<li>libc++ is installed in MacOS by XCode.</li>
</ul>
<p>Conclusion:</p>
<ul>
<li>If you're using c++11, you <strong>have</strong> to use -stdlib=libc++. </li>
<li>If you want to use boost or any other library, you have to recompile them with -stdlib=libc++ as well. </li>
</ul>
<p>So I downloaded boost sources from their website, and compiled using the following command line:</p>
<pre><code>bootstrap.sh && b2 toolset=clang cxxflags="-stdlib=libc++" linkflags="-stdlib=libc++" install
</code></pre>
<p>If you use Homebrew, you can do it with and it will do the right thing for you: </p>
<pre><code>brew install boost --c++11
</code></pre> |
22,310,912 | Bootstrap row with columns of different height | <p>I currently have something like:</p>
<pre><code><div class="row">
<div class="col-md-4">Content</div>
<div class="col-md-4">Content</div>
<div class="col-md-4">Content</div>
<div class="col-md-4">Content</div>
<div class="col-md-4">Content</div>
<div class="col-md-4">Content</div>
<div class="col-md-4">Content</div>
<div class="col-md-4">Content</div>
<div class="col-md-4">Content</div>
</div>
</code></pre>
<p>Now assuming that, <code>content</code> was boxes of different height, with all the same width - how could I keep the same "grid based layout" and yet have all the boxes line up under each other, instead of in perfect lines.</p>
<p>Currently TWBS will place the next line of <code>col-md-4</code> under the longest element in the previous third row., thus each row of items is perfectly aligned an clean - while this is awesome I want each item to fall directly under the last element ("Masonry" layout)</p> | 22,311,212 | 3 | 0 | null | 2014-03-10 20:43:50.78 UTC | 56 | 2021-07-23 12:19:46.297 UTC | 2018-04-03 11:52:03.347 UTC | null | 171,456 | null | 3,379,926 | null | 1 | 105 | html|css|twitter-bootstrap|responsive-design|bootstrap-4 | 96,535 | <p>This is a popular Bootstrap question, so I've <strong>updated</strong> and expanded the answer for Bootstrap 3, Bootstrap 4 and Bootstrap 5...</p>
<p><strong>Bootstrap 5 (update 2021)</strong></p>
<p>Bootstrap columns still use flexbox, but the card-columns previously used to create a Masonry like layout <a href="https://getbootstrap.com/docs/5.0/components/card/#masonry" rel="noreferrer">have been removed</a>. For Bootstrap 5 the recommended method is to use the Masonry JS plugin:
<a href="https://codeply.com/p/yrjCBwUeKR" rel="noreferrer">Bootstrap 5 Masonry Example</a></p>
<p><strong>Bootstrap 4 (update 2018)</strong></p>
<p>All columns are equal height in <strong>Bootstrap 4</strong> because it uses flexbox by default, so the "height issue" is not a problem. Additionally, Bootstrap 4 includes this type of multi-columns solution:
<a href="http://codeply.com/go/q03ZHDeSGN" rel="noreferrer">Bootstrap 4 Masonry cards Demo</a>.</p>
<p><strong>Bootstrap 3 (original answer -- pre flexbox)</strong></p>
<p>The <strong>Bootstrap 3</strong> "<a href="https://medium.com/wdstack/varying-column-heights-in-bootstrap-4e8dd5338643" rel="noreferrer">height problem</a>" occurs because the columns use <code>float:left</code>. When a column is “floated” it’s taken out of the normal flow of the document. It is shifted to the left or right until it touches the edge of its containing box. So, when you have <strong>uneven column heights</strong>, the correct behavior is to stack them to the closest side.</p>
<p><a href="https://i.stack.imgur.com/5oEhI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5oEhI.png" alt="Bootstrap uneven wrapping columns" /></a></p>
<p><strong>Note</strong>: The options below are applicable for <a href="https://getbootstrap.com/docs/3.3/css/#grid-example-wrapping" rel="noreferrer"><strong>column wrapping</strong> scenarios</a> where there are <strong>more than 12 col units in a single <code>.row</code></strong>. For readers that don't understand why there would ever be <strong>more than 12 cols in a row</strong>, or think the solution is to "use separate rows" <a href="https://medium.com/wdstack/bootstrap-exceed-12-columns-in-a-row-b551eeddf62b" rel="noreferrer">should read this first</a></p>
<hr>
<p><strong>There are a few ways to fix this..</strong> (updated for 2018)</p>
<p><strong>1 - The 'clearfix' approach</strong> (<a href="http://getbootstrap.com/css/#grid-responsive-resets" rel="noreferrer">recommended by Bootstrap</a>) like this (requires iteration every <em>X</em> columns). This will force a wrap every <em>X</em> number of columns...</p>
<p><a href="https://i.stack.imgur.com/Jzyn2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Jzyn2.png" alt="enter image description here" /></a></p>
<pre><code><div class="row">
<div class="col-md-4">Content</div>
<div class="col-md-4">Content</div>
<div class="col-md-4">Content</div>
<div class="clearfix"></div>
<div class="col-md-4">Content</div>
<div class="col-md-4">Content</div>
<div class="col-md-4">Content</div>
<div class="clearfix"></div>
<div class="col-md-4">Content</div>
<div class="col-md-4">Content</div>
<div class="col-md-4">Content</div>
</div>
</code></pre>
<p><a href="http://www.bootply.com/fJ0JOF7yuo" rel="noreferrer">Clearfix Demo (single tier)</a></p>
<p><a href="http://bootply.com/89910" rel="noreferrer">Clearfix Demo (responsive tiers)</a> - eg. <code>col-sm-6 col-md-4 col-lg-3</code></p>
<p>There is also a <a href="http://www.codeply.com/go/lUbs1JgXUd" rel="noreferrer">CSS-only variation</a> of the 'clearfix'<br>
<a href="http://www.codeply.com/go/6YTTnADEHq" rel="noreferrer">CSS-only clearfix with tables</a></p>
<hr>
**2 - Make the columns the same height (using flexbox):**
<p>Since the issue is caused by the <em>difference</em> in height, you can make columns <em>equal</em> height across each row. Flexbox is the best way to do this, and is <strong>natively supported in Bootstrap 4</strong>...</p>
<p><a href="https://i.stack.imgur.com/8IQZW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8IQZW.png" alt="enter image description here" /></a></p>
<pre><code>.row.display-flex {
display: flex;
flex-wrap: wrap;
}
.row.display-flex > [class*='col-'] {
display: flex;
flex-direction: column;
}
</code></pre>
<p><a href="https://www.codeply.com/go/KppyJTTbwM" rel="noreferrer">Flexbox equal height Demo</a></p>
<hr>
**3 - Un-float the columns an use inline-block instead..**
<p>Again, the height problem only occurs because the columns are floated. Another option is to set the columns to <code>display:inline-block</code> and <code>float:none</code>. This also provides more flexibility for vertical-alignment. However, with this solution there must be <strong>no HTML whitespace between columns</strong>, otherwise the <a href="https://stackoverflow.com/a/5078297/171456">inline-block elements have additional space</a> and will wrap prematurely.</p>
<p><a href="http://www.codeply.com/go/xiwLUjPz9T/bootstrap-cols-inline-block" rel="noreferrer">Demo of inline block fix</a></p>
<hr>
<p><strong>4 - CSS3 columns approach (Masonry/Pinterest like solution)..</strong></p>
<p>This is not native to Bootstrap 3, but another approach using <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Columns/Using_multi-column_layouts" rel="noreferrer">CSS multi-columns</a>. One downside to this approach is the column order is top-to-bottom instead of left-to-right. <strong>Bootstrap 4 includes this type of
solution</strong>:
<a href="http://www.codeply.com/go/q03ZHDeSGN" rel="noreferrer"><strong>Bootstrap 4 Masonry</strong> cards Demo</a>.</p>
<p><a href="http://www.bootply.com/120682" rel="noreferrer">Bootstrap 3 multi-columns Demo</a></p>
<p><strong>5 - Masonry JavaScript/jQuery approach</strong></p>
<p>Finally, you may want to use a plugin such as Isotope/Masonry:
<a href="https://i.stack.imgur.com/UJcPh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UJcPh.png" alt="enter image description here" /></a></p>
<p><a href="http://www.bootply.com/108697" rel="noreferrer">Bootstrap Masonry Demo</a><br>
<a href="http://www.codeply.com/go/UYk8DzIDv6" rel="noreferrer">Masonry Demo 2</a></p>
<hr>
<p><a href="https://medium.com/wdstack/varying-column-heights-in-bootstrap-4e8dd5338643" rel="noreferrer">More on Bootstrap Variable Height Columns</a></p>
<hr> |
31,147,660 | ImportError: No module named 'selenium' | <p>I'm trying to write a script to check a website. It's the first time I'm using selenium. I'm trying to run the script on a OSX system. Although I checked in /Library/Python/2.7/site-packages and selenium-2.46.0-py2.7.egg is present, when I run the script it keeps telling me that there is no selenium module to import.</p>
<p>This is the log that I get when I run my code:</p>
<blockquote>
<pre><code>Traceback (most recent call last):
File "/Users/GiulioColleluori/Desktop/Class_Checker.py", line 10, in <module>
from selenium import webdriver
ImportError: No module named 'selenium'
</code></pre>
</blockquote> | 31,149,093 | 21 | 0 | null | 2015-06-30 20:13:56.313 UTC | 15 | 2022-08-31 08:51:20.503 UTC | 2019-08-17 19:52:30.92 UTC | null | 1,839,439 | null | 5,066,924 | null | 1 | 78 | python|macos|selenium|module|webdriver | 404,347 | <p>If you have pip installed you can install selenium like so.</p>
<p><code>pip install selenium</code></p>
<p>or depending on your permissions:</p>
<p><code>sudo pip install selenium</code></p>
<p>For python3:</p>
<p><code>sudo pip3 install selenium</code></p>
<p>As you can see from this question <a href="https://stackoverflow.com/questions/3220404/why-use-pip-over-easy-install">pip vs easy_install</a> pip is a more reliable package installer as it was built to improve easy_install.</p>
<p>I would also suggest that when creating new projects you do so in virtual environments, even a simple selenium project. You can read more about virtual environments <a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/" rel="noreferrer">here</a>. In fact pip is included out of the box with virtualenv!</p> |
20,577,840 | python dictionary sorting in descending order based on values | <p>I want to sort this dictionary d based on value of sub key key3 in descending order. See below:</p>
<pre><code>d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
'124': { 'key1': 6, 'key2': 56, 'key3': 6 },
'125': { 'key1': 7, 'key2': 44, 'key3': 9 },
}
</code></pre>
<p>So final dictionary would look like this.</p>
<pre><code>d = { '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
'124': { 'key1': 6, 'key2': 56, 'key3': 6 },
'123': { 'key1': 3, 'key2': 11, 'key3': 3 },
}
</code></pre>
<p>My approach was to form another dictionary e from d, whose key would be value of key3 and then use reversed(sorted(e)) but since value of key3 can be same, so dictionary e lost some of the keys and their values. makes sense?</p>
<p>How I can accomplish this? This is not a tested code. I am just trying to understand the logic.</p> | 20,577,876 | 11 | 1 | null | 2013-12-13 23:38:24.52 UTC | 17 | 2022-09-08 09:38:25.993 UTC | 2013-12-13 23:39:59.7 UTC | null | 1,251,918 | null | 1,251,918 | null | 1 | 64 | python|dictionary | 206,949 | <p><a href="http://docs.python.org/3/library/stdtypes.html#dictionary-view-objects" rel="noreferrer">Dictionaries do not have any inherent order</a>. Or, rather, their inherent order is "arbitrary but not random", so it doesn't do you any good.</p>
<p>In different terms, your <code>d</code> and your <code>e</code> would be exactly equivalent dictionaries.</p>
<p>What you can do here is to use an <a href="http://docs.python.org/3/library/collections.html#ordereddict-objects" rel="noreferrer"><code>OrderedDict</code></a>:</p>
<pre><code>from collections import OrderedDict
d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
'124': { 'key1': 6, 'key2': 56, 'key3': 6 },
'125': { 'key1': 7, 'key2': 44, 'key3': 9 },
}
d_ascending = OrderedDict(sorted(d.items(), key=lambda kv: kv[1]['key3']))
d_descending = OrderedDict(sorted(d.items(),
key=lambda kv: kv[1]['key3'], reverse=True))
</code></pre>
<p>The original <code>d</code> has some arbitrary order. <code>d_ascending</code> has the order you <em>thought</em> you had in your original <code>d</code>, but didn't. And <code>d_descending</code> has the order you want for your <code>e</code>.</p>
<hr>
<p>If you don't really need to use <code>e</code> as a dictionary, but you just want to be able to iterate over the elements of <code>d</code> in a particular order, you can simplify this:</p>
<pre><code>for key, value in sorted(d.items(), key=lambda kv: kv[1]['key3'], reverse=True):
do_something_with(key, value)
</code></pre>
<hr>
<p>If you want to maintain a dictionary in sorted order across any changes, instead of an <code>OrderedDict</code>, you want some kind of sorted dictionary. There are a number of options available that you can find on PyPI, some implemented on top of trees, others on top of an <code>OrderedDict</code> that re-sorts itself as necessary, etc.</p> |
32,229,170 | Catch all possible android exception globally and reload application | <p>I know the best way to prevent system crashes is catching all possible exception in different methods. So I use try catch blocks every where in my code. However as you know sometimes you forget to test some scenarios which cause some unhanded exceptions and a user gets "Unfortunately App stopped working..." message. This is bad for any application. Unfortunately the people who will use my app are not native English, so they will not understand crash message too. </p>
<p>So I want to know is it possible to catch all possible exception globally ( with just one try catch block in some main classes not all classes and methods!!!) and <strong>reload application automatically</strong> and without any weird messages? Or at least is it possible to <strong>change the crash message</strong>?</p>
<p>Thanks.</p> | 32,229,266 | 3 | 2 | null | 2015-08-26 14:16:54.287 UTC | 16 | 2019-03-27 15:57:41.573 UTC | 2018-12-17 14:46:16.95 UTC | null | 2,965,799 | null | 2,965,799 | null | 1 | 28 | android|error-handling|try-catch | 24,514 | <p>In your onCreate</p>
<pre><code>Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
//Catch your exception
// Without System.exit() this will not work.
System.exit(2);
}
});
</code></pre> |
15,669,091 | Bower install using only https? | <p>I am trying to set up Bower on a build server at our organization's data center, but <code>git</code>'s port does not appear to be open on the data center's firewall. I can use the git command line client to clone via <code>https://[repo]</code>, but not <code>git://[repo]</code>.</p>
<p>Is there a switch or preference which will instruct bower to perform git clone using <code>https</code> rather than the <code>git</code> protocol?</p>
<p>I've looked at the source, and considered changing the resolution code to replace <code>git://</code> with <code>https://</code>, but I figured I'd ask before I go to those lengths.</p> | 15,684,898 | 3 | 1 | null | 2013-03-27 20:46:05.193 UTC | 172 | 2018-08-05 04:39:37.727 UTC | 2014-07-31 15:09:15.967 UTC | null | 991,458 | null | 182,654 | null | 1 | 258 | git|bower|git-clone | 70,960 | <p>You can make git replace the protocol for you. Just run:</p>
<pre><code>git config --global url."https://".insteadOf git://
</code></pre>
<p>to use HTTPS protocol instead of Git.</p> |
39,595,034 | Git: "Cannot 'squash' without a previous commit" error while rebase | <p>I have the following in the to-do text of <code>git rebase -i HEAD~2</code>:</p>
<pre><code>pick 56bcce7 Closes #2774
pick e43ceba Lint.py: Replace deprecated link
# Rebase 684f917..e43ceba onto 684f917 (2 command(s))
#
...
</code></pre>
<p>Now, when I try to squash the first one(<code>56bcce7</code>) and pick the second one by adding "s" before the first, I get the following error:</p>
<pre><code>Cannot 'squash' without a previous commit
</code></pre>
<p>Can someone explain me what it means, and how do I do it?</p>
<p><strong>I want to squash the first commit(<code>56bcce7</code>) and "select and reword" the second(<code>e43ceba</code>) commit</strong></p> | 39,595,642 | 7 | 2 | null | 2016-09-20 13:09:47.197 UTC | 45 | 2020-02-26 06:05:28.983 UTC | 2018-04-13 02:27:13.487 UTC | null | 33,204 | null | 4,993,513 | null | 1 | 154 | git|rebase | 132,126 | <p>Interactive rebase presents commits in the reverse order of what you are used to when using <code>git log</code>. <code>git rebase -i</code> replays the selected commits in the exact (top-down) order they are listed in the saved rebase instructions file. When squashing, the commit selected for squashing is combined with the commit that precedes it in the (edited) list, i.e. the commit from the previous line. In your case - there is no previous commit for <code>56bcce7</code>. You have to do one of the following</p>
<ul>
<li><code>git rebase -i HEAD~3</code> (if you want to squash <code>56bcce7</code> into <code>684f917</code>)</li>
<li><p>If you mean to combine <code>56bcce7</code> with <code>e43ceba</code>, and <code>e43ceba</code> doesn't depend on <code>56bcce7</code>, then simply reorder them:</p>
<pre><code>r e43ceba Lint.py: Replace deprecated link
s 56bcce7 Closes #2774
</code></pre>
<p><strong>UPDATE</strong>: <a href="https://stackoverflow.com/a/42796983/6394138">Gus's answer</a> below suggests a better way of doing the same, without reordering the two commits:</p>
<pre><code>r 56bcce7 Closes #2774
s e43ceba Lint.py: Replace deprecated link
</code></pre>
<p>This will squash/merge the two commits into one. When the interactive rebase asks for a reworded commit message for <code>56bcce7</code>, provide the commit message that describes the union of <code>56bcce7</code> and <code>e43ceba</code>.</p></li>
</ul> |
31,387,238 | C++ function returning function | <p>Where in the standard are functions returning functions disallowed? I understand they are conceptually ridiculous, but it seems to me that the grammar would allow them. According to this webpage, a "<a href="http://en.cppreference.com/w/cpp/language/function">noptr-declarator [is] any valid declarator</a>" which would include the declarator of a function:</p>
<pre><code>int f()();
</code></pre>
<hr>
<p><strong>Regarding the syntax.</strong></p>
<p>It seems to me that the syntax, as spelled out in [dcl.decl], allows</p>
<pre><code>int f(char)(double)
</code></pre>
<p>which could be interpreted as <em>the function</em> <code>f</code> <em>that takes a</em> <code>char</code> <em>and returns a function with same signature as</em> <code>int g(double)</code>.</p>
<pre><code>1 declarator:
2 ptr-declarator
3 noptr-declarator parameters-and-qualifiers trailing-return-type
4 ptr-declarator:
5 noptr-declarator
6 ptr-operator ptr-declarator
7 noptr-declarator:
8 declarator-id attribute-specifier-seq opt
9 noptr-declarator parameters-and-qualifiers
10 noptr-declarator [ constant-expression opt ] attribute-specifier-seq opt
11 ( ptr-declarator )
12 parameters-and-qualifiers:
13 ( parameter-declaration-clause ) cv-qualifier-seqAfter
</code></pre>
<p>Roughly speaking, after
1->2, 2=4, 4->6, 4->6
you should have
ptr-operator ptr-operator ptr-operator
Then, use 4->5, 5=7, 7->8 for the first declarator; use 4->5, 5=7, 7->9 for the second and third declarators. </p> | 31,387,510 | 7 | 14 | null | 2015-07-13 15:18:32.367 UTC | 11 | 2020-08-27 16:23:29.493 UTC | 2015-07-13 22:37:37.767 UTC | null | 2,549,876 | null | 2,549,876 | null | 1 | 35 | c++|c++11|standards|language-lawyer | 36,690 | <p>From [dcl.fct], pretty explicitly:</p>
<blockquote>
<p><strong>Functions shall not have a return type of type array or function</strong>, although they may have a return type of
type pointer or reference to such things. There shall be no arrays of functions, although there can be arrays
of pointers to functions.</p>
</blockquote>
<p>With C++11, you probably just want:</p>
<pre><code>std::function<int()> f();
std::function<int(double)> f(char);
</code></pre>
<hr>
<p>There is some confusion regarding the C++ grammar. The statement <code>int f(char)(double);</code> <em>can</em> be parsed according to the grammar. Here is a parse tree:</p>
<p><img src="https://i.stack.imgur.com/ecsUK.png" alt="grammar"></p>
<p>Furthermore such a parse is even meaningful based on [dcl.fct]/1:</p>
<blockquote>
<p>In a declaration <code>T D</code> where <code>D</code> has the form<br>
<code>D1</code> ( <em>parameter-declaration-clause</em> ) <em>cv-qualifier-seq</em><sub>opt</sub><br>
<em>ref-qualifier</em><sub>opt</sub> <em>exception-specification</em><sub>opt</sub> <em>attribute-specifier-seq</em><sub>opt</sub><br>
and the type of the contained <em>declarator-id</em> in the declaration <code>T D1</code> is “<em>derived-declarator-type-list</em> <code>T</code>”, the
type of the <em>declarator-id</em> in <code>D</code> is “<em>derived-declarator-type-list</em> function of (<em>parameter-declaration-clause</em> ) <em>cv-qualifier-seq</em><sub>opt</sub>
<em>ref-qualifier</em><sub>opt</sub> returning <code>T</code>”.</p>
</blockquote>
<p>In this example <code>T == int</code>, <code>D == f(char)(double)</code>, <code>D1 == f(char)</code>. The type of the <em>declarator-id</em> in <code>T D1</code> (<code>int f(char)</code>) is "function of (char) returning int". So <em>derived-declarator-type-list</em> is "function of (char) returning". Thus, the type of <code>f</code> would be read as "function of (char) returning function of (double) returning int."</p>
<p>It's ultimately much ado about nothing, as this is an explicitly disallowed declarator form. But not by the grammar. </p> |
39,100,641 | Docker service start failed | <p>I have a CentOS 7.2 VM with Docker installed. Docker service and Docker container worked normally previously. But when I tried to pull a docker image, the VM was shutdown abruptly. After I restarted the VM, the Docker service could not be started:</p>
<pre><code>[root@AY13091717064020986bZ ~]# service docker start
Redirecting to /bin/systemctl start docker.service
Job for docker.service failed because the control process exited with error code. See "systemctl status docker.service" and "journalctl -xe" for details.
</code></pre>
<p><code>systemctl status docker.service</code> output:</p>
<pre><code>[root@AY13091717064020986bZ ~]# systemctl status docker.service
● docker.service - Docker Application Container Engine
Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: disabled)
Active: failed (Result: exit-code) since Tue 2016-08-23 19:11:19 CST; 13min ago
Docs: http://docs.docker.com
Process: 1404 ExecStart=/usr/bin/docker-current daemon --exec-opt native.cgroupdriver=systemd $OPTIONS $DOCKER_STORAGE_OPTIONS $DOCKER_NETWORK_OPTIONS $ADD_REGISTRY $BLOCK_REGISTRY $INSECURE_REGISTRY (code=exited, status=1/FAILURE)
Main PID: 1404 (code=exited, status=1/FAILURE)
Aug 23 19:11:17 AY13091717064020986bZ systemd[1]: Starting Docker Application Container Engine...
Aug 23 19:11:19 AY13091717064020986bZ docker-current[1404]: time="2016-08-23T19:11:19.448828158+08:00" level=warning msg="devmapper: Usage of loopback devices is strongly discou...v section."
Aug 23 19:11:19 AY13091717064020986bZ docker-current[1404]: time="2016-08-23T19:11:19.511103592+08:00" level=error msg="[graphdriver] prior storage driver \"devicemapper\" faile...t status 2"
Aug 23 19:11:19 AY13091717064020986bZ docker-current[1404]: time="2016-08-23T19:11:19.511196844+08:00" level=fatal msg="Error starting daemon: error initializing graphdriver: de...t status 2"
Aug 23 19:11:19 AY13091717064020986bZ systemd[1]: docker.service: main process exited, code=exited, status=1/FAILURE
Aug 23 19:11:19 AY13091717064020986bZ systemd[1]: Failed to start Docker Application Container Engine.
Aug 23 19:11:19 AY13091717064020986bZ systemd[1]: Unit docker.service entered failed state.
Aug 23 19:11:19 AY13091717064020986bZ systemd[1]: docker.service failed.
Hint: Some lines were ellipsized, use -l to show in full.
</code></pre>
<p>"<code>journalctl -xe</code>" output:</p>
<pre><code>[root@AY13091717064020986bZ ~]# journalctl -xe
Aug 23 19:11:19 AY13091717064020986bZ kernel: device-mapper: block manager: btree_node validator check failed for block 146
Aug 23 19:11:19 AY13091717064020986bZ kernel: device-mapper: btree spine: node_check failed: csum 1600702373 != wanted 1600827965
Aug 23 19:11:19 AY13091717064020986bZ kernel: device-mapper: block manager: btree_node validator check failed for block 146
Aug 23 19:11:19 AY13091717064020986bZ kernel: Buffer I/O error on device dm-1, logical block 2621424
Aug 23 19:11:19 AY13091717064020986bZ docker-current[1404]: time="2016-08-23T19:11:19.511103592+08:00" level=error msg="[graphdriver] prior storage driver \"devicemapper\" failed: devmapper:
Aug 23 19:11:19 AY13091717064020986bZ docker-current[1404]: time="2016-08-23T19:11:19.511196844+08:00" level=fatal msg="Error starting daemon: error initializing graphdriver: devmapper: Base
Aug 23 19:11:19 AY13091717064020986bZ systemd[1]: docker.service: main process exited, code=exited, status=1/FAILURE
Aug 23 19:11:19 AY13091717064020986bZ systemd[1]: Failed to start Docker Application Container Engine.
-- Subject: Unit docker.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit docker.service has failed.
--
-- The result is failed.
Aug 23 19:11:19 AY13091717064020986bZ systemd[1]: Unit docker.service entered failed state.
Aug 23 19:11:19 AY13091717064020986bZ systemd[1]: docker.service failed.
Aug 23 19:11:19 AY13091717064020986bZ polkitd[1014]: Unregistered Authentication Agent for unix-process:1370:16052 (system bus name :1.22, object path /org/freedesktop/PolicyKit1/Authenticati
Aug 23 19:23:43 AY13091717064020986bZ systemd[1]: Starting Cleanup of Temporary Directories...
-- Subject: Unit systemd-tmpfiles-clean.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit systemd-tmpfiles-clean.service has begun starting up.
Aug 23 19:23:43 AY13091717064020986bZ systemd[1]: Started Cleanup of Temporary Directories.
-- Subject: Unit systemd-tmpfiles-clean.service has finished start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit systemd-tmpfiles-clean.service has finished starting up.
--
-- The start-up result is done.
</code></pre>
<p>Docker version:</p>
<pre><code>[root@AY13091717064020986bZ ~]# docker version
Client:
Version: 1.10.3
API version: 1.22
Package version: docker-common-1.10.3-46.el7.centos.10.x86_64
Go version: go1.6.3
Git commit: d381c64-unsupported
Built: Thu Aug 4 13:21:17 2016
OS/Arch: linux/amd64
Cannot connect to the Docker daemon. Is the docker daemon running on this host?
</code></pre>
<p>Linux kernel version:</p>
<pre><code>[root@AY13091717064020986bZ ~]# uname -a
Linux AY13091717064020986bZ 3.10.0-327.el7.x86_64 #1 SMP Thu Nov 19 22:10:57 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
[root@AY13091717064020986bZ ~]#
</code></pre>
<p>CentOS version:</p>
<pre><code>[root@AY13091717064020986bZ ~]# lsb_release -a
LSB Version: :core-4.1-amd64:core-4.1-noarch
Distributor ID: CentOS
Description: CentOS Linux release 7.2.1511 (Core)
Release: 7.2.1511
Codename: Core
[root@AY13091717064020986bZ ~]#
</code></pre> | 44,467,263 | 13 | 3 | null | 2016-08-23 12:02:57.06 UTC | 12 | 2022-06-09 13:28:35.717 UTC | 2018-08-03 02:55:04.547 UTC | null | 63,550 | null | 2,674,239 | null | 1 | 51 | docker|centos7 | 187,889 | <p>I had a similar issue. This was how I fixed it permanently:</p>
<ul>
<li>Delete everything in <code>/var/lib/docker</code>. This will delete existing container and images:</li>
</ul>
<pre><code>rm -rf /var/lib/docker
</code></pre>
<ul>
<li>Then configure your daemon to use the "overlay" storage driver. Set the following flags in <code>/etc/docker/daemon.json</code>. If the file doesn't exist, just create it, and add the contents below:</li>
</ul>
<pre class="lang-json prettyprint-override"><code>{
"graph": "/mnt/docker-data",
"storage-driver": "overlay"
}
</code></pre>
<p>Now start Docker normally again and all should work fine and always.</p>
<p>See <em><a href="https://docs.docker.com/engine/admin/systemd/#start-automatically-at-system-boot" rel="noreferrer">Start automatically at system boot</a></em>.</p> |
19,845,950 | AngularJS How to dynamically add HTML and bind to controller | <p>I'm just getting started with angularJS and struggling to figure out proper architecture for what I'm trying to do. I have a single page app but <strong>the URL always should stay the same</strong>; I don't want the user to be able to navigate to any routes beyond the root. In my app, there is one main div that will need to host different views. When a new view is accessed, I want it to take over the display in the main div. Views loaded in this way can be throw-away or stick around as hidden in the DOM - I'm interested in seeing how each might work.</p>
<p>I've come up with a rough working example of what I'm trying to do. <a href="http://plnkr.co/edit/2mtezdA9P9dkixzbvELU?p=preview">See working example here in this Plunk.</a> Basically I want to dynamically load HTML into the DOM and have standard angularJS controllers be able to hook into that new HTML. Is there a better/simpler way to do this than by using the custom directive I have here and using $compile() to hook up to angular? Perhaps there's something sort of like the router, but doesn't require URL has changes to operate?</p>
<p>Here's the special directive I'm using so far (taken from another SO post):</p>
<pre><code>// Stolen from: http://stackoverflow.com/questions/18157305/angularjs-compiling-dynamic-html-strings-from-database
myApp.directive('dynamic', function ($compile) {
return {
replace: true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function(html) {
if (!html) {
return;
}
ele.html((typeof(html) === 'string') ? html : html.data);
$compile(ele.contents())(scope);
});
}
};
});
</code></pre>
<p>Thanks,</p>
<p>Andy</p> | 19,846,600 | 5 | 1 | null | 2013-11-07 20:24:20.757 UTC | 19 | 2017-08-23 13:28:38.737 UTC | null | null | null | null | 152,517 | null | 1 | 58 | javascript|angularjs | 210,599 | <p>I would use the built-in <a href="http://docs.angularjs.org/api/ng.directive:ngInclude" rel="noreferrer"><code>ngInclude</code></a> directive. In the example below, you don't even need to write any javascript. The templates can just as easily live at a remote url.</p>
<p>Here's a working demo: <a href="http://plnkr.co/edit/5ImqWj65YllaCYD5kX5E?p=preview" rel="noreferrer">http://plnkr.co/edit/5ImqWj65YllaCYD5kX5E?p=preview</a></p>
<pre><code><p>Select page content template via dropdown</p>
<select ng-model="template">
<option value="page1">Page 1</option>
<option value="page2">Page 2</option>
</select>
<p>Set page content template via button click</p>
<button ng-click="template='page2'">Show Page 2 Content</button>
<ng-include src="template"></ng-include>
<script type="text/ng-template" id="page1">
<h1 style="color: blue;">This is the page 1 content</h1>
</script>
<script type="text/ng-template" id="page2">
<h1 style="color:green;">This is the page 2 content</h1>
</script>
</code></pre> |
7,588,142 | MySQL Left Join + Min | <p>Seemingly simple MySQL question, but I've never had to do this before..</p>
<p>I have two tables, items and prices, with a one-to-many relationship. </p>
<pre><code>Items Table
id, name
Prices Table
id, item_id, price
</code></pre>
<p>Where</p>
<pre><code>prices.item_id = items.id
</code></pre>
<p>What I have so far:</p>
<pre><code>SELECT items.id, items.name, MIN(prices.price)
FROM items
LEFT JOIN prices ON items.id = prices.item_id
GROUP BY items.id
</code></pre>
<p>How do I also return the corresponding prices.id for that minimum price? Thanks!</p> | 7,588,442 | 4 | 1 | null | 2011-09-28 18:58:21.213 UTC | 8 | 2017-03-08 18:20:56.613 UTC | 2011-09-28 19:01:13.583 UTC | null | 73,226 | null | 616,946 | null | 1 | 22 | mysql|group-by|left-join|greatest-n-per-group|min | 39,569 | <p>This will return multiple records for a record in Items if there are multiple Prices records for it with the minimum price:</p>
<pre><code>select items.id, items.name, prices.price, prices.id
from items
left join prices on (
items.id = prices.item_id
and prices.price = (
select min(price)
from prices
where item_id = items.id
)
);
</code></pre> |
7,239,996 | Android DownloadManager API - opening file after download? | <p>I am facing problem of opening downloaded file after successfull download via DownloadManager API. In my code:</p>
<pre><code>Uri uri=Uri.parse("http://www.nasa.gov/images/content/206402main_jsc2007e113280_hires.jpg");
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.mkdirs();
lastDownload = mgr.enqueue(new DownloadManager.Request(uri)
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle("app update")
.setDescription("New version 1.1")
.setShowRunningNotification(true)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "a.apk"));
Cursor c=mgr.query(new DownloadManager.Query().setFilterById(lastDownload));
if(c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)) == 8) {
try {
mgr.openDownloadedFile(c.getLong(c.getColumnIndex(DownloadManager.COLUMN_ID)));
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("MGR", "Error");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("MGR", "Error");
}
}
</code></pre>
<p>Problem is when is <code>if(c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS))==8)</code> evoked. I got status -1 and an exception. Is there any better way, how to open downloaded files with <code>DownloadManager API</code>? In my example I am downloading a big image, in a real situation I would be downloading an <code>APK</code> file and I need to display an installation dialog immediately after udpate.</p>
<p><strong>Edit:</strong> I figured out that status=8 is after successfull download. You might have different "checking successfull download" approach</p>
<p>Thanks</p> | 7,240,108 | 4 | 0 | null | 2011-08-30 07:33:13.953 UTC | 18 | 2020-11-06 09:41:25.057 UTC | 2018-10-31 16:32:50.92 UTC | null | 973,919 | null | 513,956 | null | 1 | 37 | android|download-manager | 63,573 | <p>You need to register a reciever for when the download is complete:</p>
<pre><code>registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
</code></pre>
<p>and a BroadcastReciever handler</p>
<pre><code>BroadcastReceiver onComplete=new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
// Do Something
}
};
</code></pre>
<p>Buy instead of me ripping off everything, I suggest you'll check <a href="https://github.com/commonsguy/cw-android/blob/master/Internet/Download/src/com/commonsware/android/download/DownloadDemo.java">this out</a>.</p>
<p><strong>EDIT:</strong> </p>
<p>Just as a suggestion, I wouldn't recommend using API 9 just yet: <code>http://developer.android.com/resources/dashboard/platform-versions.html</code></p>
<p>There are ways around this, by creating your very own download handler, like I did, because we didn't want to alienate most of our android's user base, for that you'll need:
Create <a href="http://developer.android.com/reference/android/os/AsyncTask.html">AsyncTask</a> which handles the file download.</p>
<p>and i'll recommend to create a download dialog of some sort (if you say it's a big file, i'd make it appear in the notification area).</p>
<p>and than you'll need to handle the opening of the file:</p>
<pre><code>protected void openFile(String fileName) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(Uri.fromFile(new File(fileName)),
"MIME-TYPE");
startActivity(install);
}
</code></pre> |
8,303,004 | Define TRACE Constant in .NET / Visual Studio | <p>In Visual Studio 2010, if you go to a project's properties and go to the Build Tab, there is a checkbox for "Define TRACE Constant." Which is the equivalent of doing a #define TRACE. </p>
<p>All of the methods of System.Diagnostics.Trace have a <code>[Conditional("TRACE")]</code> around them. </p>
<p>My question is <em>why</em> would you ever turn this off? I mean, if you don't have any trace listeners defined, then it isn't as if you're going to fill up a log or something. It just feels weird to me. If you are going through the effort to put in calls to Trace, why would you want to not control it through the App/Web.config, but instead control it via a compiler switch, which rules out the possibility of turning it back on without a recompile. </p>
<p>Am I missing something? Surely, it can't be THAT bad for performance, right? </p> | 8,303,959 | 1 | 3 | null | 2011-11-28 22:04:09.077 UTC | 5 | 2014-05-04 15:38:06.37 UTC | null | null | null | null | 82,208 | null | 1 | 46 | visual-studio|performance|debugging | 27,085 | <p>Presumably this checkbox is equivalent to the <code>/define:TRACE</code> compiler option. You might want to turn this option off for a release build either because you don't want end users to see the trace output for some reason (e.g. security), or to improve performance. Of course, the performance increase will depend on how much work is being done when it's on, but the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx">Conditional attribute</a> will cause the compiler to completely remove the function call (including any string formatting, etc.) from the generated IL, so it <em>could</em> make a significant difference.</p> |
8,241,821 | Proper use of the HsOpenSSL API to implement a TLS Server | <p>I'm trying to figure out how to properly use the <a href="http://hackage.haskell.org/packages/archive/HsOpenSSL/0.10.3.1/doc/html/OpenSSL-Session.html" rel="noreferrer">OpenSSL.Session</a> API in a concurrent context</p>
<p>E.g. assume I want to implement a <code>stunnel-style ssl-wrapper</code>, I'd expect to have the following basic skeleton structure, which implements a naive <code>full-duplex tcp-port-forwarder:</code></p>
<pre><code>runProxy :: PortID -> AddrInfo -> IO ()
runProxy localPort@(PortNumber lpn) serverAddrInfo = do
listener <- listenOn localPort
forever $ do
(sClient, clientAddr) <- accept listener
let finalize sServer = do
sClose sServer
sClose sClient
forkIO $ do
tidToServer <- myThreadId
bracket (connectToServer serverAddrInfo) finalize $ \sServer -> do
-- execute one 'copySocket' thread for each data direction
-- and make sure that if one direction dies, the other gets
-- pulled down as well
bracket (forkIO (copySocket sServer sClient
`finally` killThread tidToServer))
(killThread) $ \_ -> do
copySocket sClient sServer -- "controlling" thread
where
-- |Copy data from source to dest until EOF occurs on source
-- Copying may also be aborted due to exceptions
copySocket :: Socket -> Socket -> IO ()
copySocket src dst = go
where
go = do
buf <- B.recv src 4096
unless (B.null buf) $ do
B.sendAll dst buf
go
-- |Create connection to given AddrInfo target and return socket
connectToServer saddr = do
sServer <- socket (addrFamily saddr) Stream defaultProtocol
connect sServer (addrAddress saddr)
return sServer
</code></pre>
<p>How do I transform the above skeleton into a <code>full-duplex ssl-wrapping tcp-forwarding proxy</code>? Where are the dangers W.R.T to concurrent/parallel execution (in the context of the above use-case) of the function calls provided by the HsOpenSSL API?</p>
<p>PS: I'm still struggling to fully comprehend how to make the code robust w.r.t. to exceptions and resource-leaks. So, albeit not being the primary focus of this question, if you notice something bad in the code above, please leave a comment.</p> | 11,406,599 | 1 | 4 | null | 2011-11-23 12:00:49.63 UTC | 8 | 2012-07-13 20:55:50.91 UTC | 2012-07-13 20:55:50.91 UTC | null | 170,339 | null | 480,398 | null | 1 | 139 | haskell|openssl|ssl | 3,696 | <p>To do this you need to replace <code>copySocket</code> with two different functions, one to handle data from the plain socket to SSL and the other from SSL to the plain socket:</p>
<pre><code> copyIn :: SSL.SSL -> Socket -> IO ()
copyIn src dst = go
where
go = do
buf <- SSL.read src 4096
unless (B.null buf) $ do
SB.sendAll dst buf
go
copyOut :: Socket -> SSL.SSL -> IO ()
copyOut src dst = go
where
go = do
buf <- SB.recv src 4096
unless (B.null buf) $ do
SSL.write dst buf
go
</code></pre>
<p>Then you need to modify <code>connectToServer</code> so that it establishes an SSL connection</p>
<pre><code> -- |Create connection to given AddrInfo target and return socket
connectToServer saddr = do
sServer <- socket (addrFamily saddr) Stream defaultProtocol
putStrLn "connecting"
connect sServer (addrAddress saddr)
putStrLn "establishing ssl context"
ctx <- SSL.context
putStrLn "setting ciphers"
SSL.contextSetCiphers ctx "DEFAULT"
putStrLn "setting verfication mode"
SSL.contextSetVerificationMode ctx SSL.VerifyNone
putStrLn "making ssl connection"
sslServer <- SSL.connection ctx sServer
putStrLn "doing handshake"
SSL.connect sslServer
putStrLn "connected"
return sslServer
</code></pre>
<p>and change <code>finalize</code> to shut down the SSL session</p>
<pre><code>let finalize sServer = do
putStrLn "shutting down ssl"
SSL.shutdown sServer SSL.Unidirectional
putStrLn "closing server socket"
maybe (return ()) sClose (SSL.sslSocket sServer)
putStrLn "closing client socket"
sClose sClient
</code></pre>
<p>Finally, don't forget to run your main stuff within <code>withOpenSSL</code> as in</p>
<pre><code>main = withOpenSSL $ do
let hints = defaultHints { addrSocketType = Stream, addrFamily = AF_INET }
addrs <- getAddrInfo (Just hints) (Just "localhost") (Just "22222")
let addr = head addrs
print addr
runProxy (PortNumber 11111) addr
</code></pre> |
2,141,799 | & or & what should be used for & (ampersand) if we are using UTF-8 in an XHTML document? | <p>What is the difference between <code>&amp;</code> and <code>&#38;</code> for & (ampersand)?</p>
<p>What should be used with UTF-8?</p> | 2,141,825 | 4 | 1 | null | 2010-01-26 18:55:13.03 UTC | 3 | 2021-11-10 03:02:36.047 UTC | 2021-11-10 02:58:26.647 UTC | null | 63,550 | null | 84,201 | null | 1 | 25 | html|xhtml|html-entities | 55,736 | <p>Both are <a href="http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.3" rel="noreferrer">character references</a> and refer to the same character (<em>AMPERSAND</em>, U+0026). <code>&amp;</code> is a named or entity character reference and <code>&#38;</code> is a numerical character reference.</p>
<p>In fact, <code>&amp;</code> is actually just a substitution for <code>&#38;</code> (see <a href="http://www.w3.org/TR/html4/sgml/entities.html" rel="noreferrer">list of character entities</a>):</p>
<blockquote>
<pre><code><!ENTITY amp CDATA "&#38;" -- ampersand, U+0026 ISOnum -->
</code></pre>
</blockquote> |
1,785,615 | #region analogue for eclipse | <p>can somebody tell me, is there an analogue of a Visual Studio #region feature for Eclipse IDE ?<br>
I really need this magic! :)</p> | 1,785,647 | 4 | 1 | null | 2009-11-23 20:08:19.81 UTC | 4 | 2013-10-21 15:13:37.213 UTC | null | null | null | null | 189,017 | null | 1 | 33 | visual-studio|eclipse|ide|region | 17,814 | <p>User-defined regions for code folding can be added by using the <a href="http://code.google.com/p/coffee-bytes/" rel="noreferrer">Coffee-Bytes</a> plugin.</p> |
10,576,686 | C# regex pattern to extract urls from given string - not full html urls but bare links as well | <p>I need a regex which will do the following</p>
<pre><code>Extract all strings which starts with http://
Extract all strings which starts with www.
</code></pre>
<p>So i need to extract these 2.</p>
<p>For example there is this given string text below</p>
<pre><code>house home go www.monstermmorpg.com nice hospital http://www.monstermmorpg.com this is incorrect url http://www.monstermmorpg.commerged continue
</code></pre>
<p>So from the given above string i will get</p>
<pre><code> www.monstermmorpg.com
http://www.monstermmorpg.com
http://www.monstermmorpg.commerged
</code></pre>
<p>Looking for regex or another way. Thank you.</p>
<p>C# 4.0</p> | 10,576,770 | 3 | 2 | null | 2012-05-14 01:45:30.68 UTC | 16 | 2021-09-13 15:43:45.203 UTC | null | null | null | null | 310,370 | null | 1 | 36 | c#|regex|url|hyperlink|extract | 49,470 | <p>You can write some pretty simple regular expressions to handle this, or go via more traditional string splitting + LINQ methodology.</p>
<h3>Regex</h3>
<pre><code>var linkParser = new Regex(@"\b(?:https?://|www\.)\S+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);
var rawString = "house home go www.monstermmorpg.com nice hospital http://www.monstermmorpg.com this is incorrect url http://www.monstermmorpg.commerged continue";
foreach(Match m in linkParser.Matches(rawString))
MessageBox.Show(m.Value);
</code></pre>
<p><strong>Explanation</strong>
Pattern:</p>
<pre><code>\b -matches a word boundary (spaces, periods..etc)
(?: -define the beginning of a group, the ?: specifies not to capture the data within this group.
https?:// - Match http or https (the '?' after the "s" makes it optional)
| -OR
www\. -literal string, match www. (the \. means a literal ".")
) -end group
\S+ -match a series of non-whitespace characters.
\b -match the closing word boundary.
</code></pre>
<p>Basically the pattern looks for strings that start with <code>http:// OR https:// OR www. (?:https?://|www\.)</code> and then matches all the characters up to the next whitespace.</p>
<h3>Traditional String Options</h3>
<pre><code>var rawString = "house home go www.monstermmorpg.com nice hospital http://www.monstermmorpg.com this is incorrect url http://www.monstermmorpg.commerged continue";
var links = rawString.Split("\t\n ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Where(s => s.StartsWith("http://") || s.StartsWith("www.") || s.StartsWith("https://"));
foreach (string s in links)
MessageBox.Show(s);
</code></pre> |
26,254,619 | Position of the legend in a Bokeh plot | <p>Does anyone know how to carry the legend in bokeh <strong>outside</strong> of the graph? The only manipulation I could do was to choose a position among:</p>
<pre><code>top_right, top_left, bottom_left or bottom_right
</code></pre>
<p>using:</p>
<pre><code>legend()[0].orientation = "bottom_left"
</code></pre>
<p>and when I try different ones I get the error message:</p>
<pre><code>ValueError: invalid value for orientation: 'outside'; allowed values are top_right, top_left, bottom_left or bottom_right
</code></pre> | 38,146,264 | 2 | 1 | null | 2014-10-08 10:25:58.617 UTC | 8 | 2021-06-02 20:40:06.317 UTC | 2015-04-13 12:29:00.45 UTC | null | 1,251,007 | null | 3,245,539 | null | 1 | 24 | python|visualization|bokeh | 29,323 | <p>As of Bokeh <code>0.12.4</code> it is possible to position legends outside the central plot area. Here is a short example <a href="https://docs.bokeh.org/en/latest/docs/user_guide/styling.html#outside-the-plot-area" rel="nofollow noreferrer">from the user's guide</a>:</p>
<pre><code>import numpy as np
from bokeh.models import Legend
from bokeh.plotting import figure, show, output_file
x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)
output_file("legend_labels.html")
p = figure(toolbar_location="above")
r0 = p.circle(x, y)
r1 = p.line(x, y)
r2 = p.line(x, 2*y, line_dash=[4, 4], line_color="orange", line_width=2)
r3 = p.square(x, 3*y, fill_color=None, line_color="green")
r4 = p.line(x, 3*y, line_color="green")
legend = Legend(items=[
("sin(x)", [r0, r1]),
("2*sin(x)", [r2]),
("3*sin(x)", [r3, r4])
], location=(0, -30))
p.add_layout(legend, 'right')
show(p)
</code></pre>
<p>To adjust the position, change <code>dx</code> and <code>dy</code> in <code>location=(dx, dy)</code>.</p>
<p><a href="https://i.stack.imgur.com/QYvUX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QYvUX.png" alt="enter image description here"></a></p> |
7,202,453 | SVN Revert Trunk, remove a revision as if it never existed? | <p>Is it possible in the svn server to remove a revision as if it never existed?</p>
<p>So we have the following revisions:</p>
<pre><code>1004 // Commit of some bogus code that broke the build and was just wrong
1003 // Change 1.2
1002 // Change 1.1
1001
1000 *** Initial checkin
</code></pre>
<p>Can we we remove the 1004 in svn and revert back to 1003 as if 1004 never existed?</p>
<p>Forgive my ignorance, I'm still learning how to use SVN. </p> | 7,202,483 | 5 | 0 | null | 2011-08-26 09:11:31.09 UTC | 2 | 2016-10-18 19:25:22.84 UTC | 2011-08-30 09:24:59.89 UTC | null | 358,297 | null | 358,297 | null | 1 | 14 | svn|revision|revert|svn-trunk | 40,427 | <p>VCS systems are designed specifically to make this as complicated as possible. You usually do not want to do this.</p>
<p>That being said, from the official documentation:</p>
<blockquote>
<p>There are special cases where you might want to destroy all evidence of a file or commit. (Perhaps somebody accidentally committed a confidential document.) This isn't so easy, because Subversion is deliberately designed to never lose information. Revisions are immutable trees which build upon one another. Removing a revision from history would cause a domino effect, creating chaos in all subsequent revisions and possibly invalidating all working copies.</p>
<p>The project has plans, however, to someday implement an <code>svnadmin obliterate</code> command which would accomplish the task of permanently deleting information. (See <a href="http://subversion.tigris.org/issues/show_bug.cgi?id=516" rel="noreferrer">issue 516</a>.)</p>
<p>In the meantime, your only recourse is to <code>svnadmin dump</code> your repository, then pipe the dumpfile through <code>svndumpfilter</code> (excluding the bad path) into an <code>svnadmin load</code> command. See <a href="http://svnbook.red-bean.com/nightly/en/svn.reposadmin.html" rel="noreferrer">chapter 5</a> of the Subversion book for details about this.</p>
</blockquote>
<p><a href="http://subversion.apache.org/faq.html#removal" rel="noreferrer">http://subversion.apache.org/faq.html#removal</a></p> |
7,519,423 | jQuery - How to get attribute of an element when using the 'click' event | <p>I'm using jQuery to get a click on an 'a' element. I have a list of those links where each one has a class which by him I'm capturing the click.</p>
<p>I would like to know which of the links has been clicked (I have an attribute 'setid' for each link) and also get the point where the mouse has been clicked.</p>
<p>How could this be accomplished?</p>
<p>example of the code:</p>
<pre><code><a href="#" class="newItem" setid="28">click me</a>
$('.newItem').click(function (e) {
alert(e.attr('setid'));
});
</code></pre>
<p>EDIT:
OK, so to get the position I would use e.pageX</p> | 7,519,435 | 5 | 2 | null | 2011-09-22 18:09:41.153 UTC | 7 | 2015-08-09 08:16:37.093 UTC | null | null | null | null | 239,279 | null | 1 | 28 | javascript|jquery | 69,615 | <p>To use jQuery methods you have to wrap <strong>this</strong> with a call to jQuery. </p>
<pre><code>$('.newItem').click(function () {
alert($(this).attr('setid'));
});
</code></pre> |
7,670,280 | Tree plotting in Python | <p>I want to plot trees using Python. Decision trees, Organizational charts, etc. Any library that helps me with that?</p> | 7,673,423 | 6 | 0 | null | 2011-10-06 04:22:51.473 UTC | 32 | 2021-09-02 15:25:53.75 UTC | 2021-03-13 12:54:24.883 UTC | null | 2,956,066 | null | 405,126 | null | 1 | 69 | python|plot|tree|data-visualization|visualization | 131,743 | <p>There's graphviz - <a href="http://www.graphviz.org/" rel="noreferrer">http://www.graphviz.org/</a>. It uses the "DOT" language to plot graphs. You can either generate the DOT code yourself, or use pydot - <a href="https://github.com/pydot/pydot" rel="noreferrer">https://github.com/pydot/pydot</a>. You could also use networkx - <a href="http://networkx.lanl.gov/tutorial/tutorial.html#drawing-graphs" rel="noreferrer">http://networkx.lanl.gov/tutorial/tutorial.html#drawing-graphs</a>, which make it easy to draw to either graphviz or matplotlib.</p>
<p>networkx + matplotlib + graphviz gives you the most flexibility and power, but you need to install a lot.</p>
<p>If you want a quick solution, try:</p>
<p>Install Graphviz.</p>
<pre><code>open('hello.dot','w').write("digraph G {Hello->World}")
import subprocess
subprocess.call(["path/to/dot.exe","-Tpng","hello.dot","-o","graph1.png"])
# I think this is right - try it form the command line to debug
</code></pre>
<p>Then you install pydot, because pydot already does this for you. Then you can use networkx to "drive" pydot.</p> |
7,605,785 | splitting a string based on multiple char delimiters | <p>I have a string "4,6,8\n9,4"</p>
<p>I want to split this based on ,and \n</p>
<p>Output array should be </p>
<pre><code>4
6
8
9
4
</code></pre>
<p><strong>Edit :</strong></p>
<p>Now i am reading string from console , when i enter a string as above in console , in the code behind i get as <code>"4,6,8\\n9,4"</code> . Now that i want to split using <code>"," and "\\n"</code> . How can i change the expression ? </p> | 7,605,801 | 6 | 0 | null | 2011-09-30 03:58:10.043 UTC | 7 | 2022-04-01 09:16:05.413 UTC | 2011-09-30 04:16:09.34 UTC | null | 769,091 | null | 769,091 | null | 1 | 81 | c#|.net|string|split | 112,475 | <p>Use <a href="http://msdn.microsoft.com/en-us/library/b873y76a.aspx" rel="noreferrer">string.Split(char [])</a></p>
<pre><code>string strings = "4,6,8\n9,4";
string [] split = strings .Split(new Char [] {',' , '\n' });
</code></pre>
<p><strong>EDIT</strong></p>
<p>Try following if you get any unnecessary empty items. <a href="http://msdn.microsoft.com/en-us/library/tabh47cf.aspx" rel="noreferrer">String.Split Method (String[], StringSplitOptions)</a></p>
<pre><code>string [] split = strings .Split(new Char [] {',' , '\n' },
StringSplitOptions.RemoveEmptyEntries);
</code></pre>
<p><strong>EDIT2</strong></p>
<p>This works for your updated question. Add all the necessary split characters to the <code>char []</code>. </p>
<pre><code>string [] split = strings.Split(new Char[] { ',', '\\', '\n' },
StringSplitOptions.RemoveEmptyEntries);
</code></pre> |
7,138,119 | Saving facebook id as int or varchar? | <p>My question is more advisory than technical.
I'm writing a Facebook app in which I am fetching some information about the user, including facebook_id.<br>
I was wondering if I should keep the user id as INT or VARCHAR in the MySQL database?</p> | 7,138,309 | 7 | 1 | null | 2011-08-21 12:02:00.517 UTC | 6 | 2015-03-16 07:31:18.11 UTC | 2011-08-21 12:49:49.58 UTC | null | 762,449 | null | 536,912 | null | 1 | 37 | mysql|facebook|facebook-graph-api | 32,838 | <p>Facebook uses <strong>64-bit integers (bigint)</strong> for their user ids. So you use Bigint UNSIGNED in MySQL.</p>
<p><a href="https://developers.facebook.com/blog/post/226" rel="noreferrer">"As a reminder, in the very near future, we will be rolling out 64 bit user IDs. We encourage you to test your applications by going to www.facebook.com/r.php?force_64bit and create test accounts with 64 bit UIDs."</a></p>
<p>Edit: Facebook usernames is not the same thing as the user id. The username is of course varchar but will not be returned as the id.</p> |
7,369,945 | Algorithm for maze generation with no dead ends? | <p>I'm looking for a maze generation algorithm that can generate mazes with no dead ends but only a start and end. Like this: </p>
<p><img src="https://i.stack.imgur.com/izywL.gif" alt="maze"></p>
<p><sub>Image from <a href="http://www.astrolog.org/labyrnth/maze/unicursl.gif" rel="noreferrer">http://www.astrolog.org/labyrnth/maze/unicursl.gif</a></sub></p>
<p>Where do I find or go about constructing such a maze generation algorithm?</p> | 7,370,232 | 8 | 6 | null | 2011-09-10 05:57:43.373 UTC | 12 | 2020-09-13 01:40:39.03 UTC | 2013-12-18 23:23:29.43 UTC | null | 321,731 | null | 912,387 | null | 1 | 35 | algorithm|maze | 11,925 | <p>It sounds like you want a pseudo-random space filling curve (for example, see <em><a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.35.3648&rep=rep1&type=pdf">Context-based Space Filling Curves -EUROGRAPHICS ’2000</a></em> (PDF format, 1.1 MB))</p>
<p>Take a look a <em><a href="http://en.wikipedia.org/wiki/Space-filling_curve">Space-filling curve</a></em>.</p>
<p>I suspect you could apply some randomness to the construction of one of these to achieve what you want.</p> |
13,877,405 | What is wrong on this Decimal.TryParse? | <p>Code :</p>
<pre><code>Decimal kilometro = Decimal.TryParse(myRow[0].ToString(), out decimal 0);
</code></pre>
<p>some arguments are not valid?</p> | 13,877,421 | 4 | 0 | null | 2012-12-14 11:04:28.503 UTC | 1 | 2019-11-07 14:29:43.353 UTC | null | null | null | null | 365,251 | null | 1 | 8 | c#|tryparse | 57,956 | <p><code>out decimal 0</code> is not a valid parameter - <code>0</code> is not a valid variable name.</p>
<pre><code>decimal output;
kilometro = decimal.TryParse(myRow[0].ToString(), out output);
</code></pre>
<p>By the way, the return value will be a <code>bool</code> - from the name of the variable, your code should probably be:</p>
<pre><code>if(decimal.TryParse(myRow[0].ToString(), out kilometro))
{
// success - can use kilometro
}
</code></pre>
<p>Since you want to return <code>kilometro</code>, you can do:</p>
<pre><code>decimal kilometro = 0.0; // Not strictly required, as the default value is 0.0
decimal.TryParse(myRow[0].ToString(), out kilometro);
return kilometro;
</code></pre> |
13,925,724 | providedCompile without war plugin | <p>I want to reuse certain filter for many projects so I want to extract it and use a single jar to just add it to any Web App.</p>
<p>For building I am using Gradle 1.3 and the following <code>build.gradle</code> file:</p>
<pre><code>apply plugin: 'java'
dependencies {
compile group:'org.slf4j', name:'slf4j-api', version:'1.7.+'
testCompile group:'junit', name:'junit', version:'4.+'
compile group:'org.springframework', name:'spring-web', version:'3.+'
compile group:'org.slf4j', name:'slf4j-log4j12', version:'1.6.+'
compile group:'log4j', name:'log4j', version:'1.2.+'
providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version:'3.+'
}
repositories {
mavenCentral()
}
</code></pre>
<p>As you can see, I need the servlet api to compile this filter succesfully so I want to add it like a maven provided dependency. </p>
<p>Anyways, after running <code>gradle build</code> I get the following error:</p>
<blockquote>
<p>Could not find method providedCompile() for arguments
[{group=javax.servlet, name=javax.servlet-api, version=3.+}] on root
project 'hibernate-conversation-context'.</p>
</blockquote>
<p>Now, I know that I cannot use providedCompile without the WAR plugin but I need the project to be a simple JAR. Is there another way to do this?</p> | 13,932,897 | 7 | 1 | null | 2012-12-18 03:15:22.423 UTC | 17 | 2016-10-27 13:55:39.687 UTC | null | null | null | null | 1,391,333 | null | 1 | 40 | gradle | 34,315 | <p>There is no such configuration out of the box for the <code>java</code> plugin. However you can build it yourself as follows:</p>
<pre><code>configurations { providedCompile }
dependencies {
providedCompile "javax.servlet:javax.servlet-api:3.+"
}
sourceSets.main.compileClasspath += configurations.providedCompile
sourceSets.test.compileClasspath += configurations.providedCompile
sourceSets.test.runtimeClasspath += configurations.providedCompile
</code></pre>
<p>This adds the configuration, and puts all the dependencies in there on the compile classpaths of both your main classes and test classes. You also need to add it to the runtimeClasspath, as that doesn't include the compile classpath according to the gradle DSL documentation.</p> |
14,099,770 | Casperjs/PhantomJs vs Selenium | <p>We are using Selenium to automate our <code>UI</code> testing. Recently we have seen majority of our users using Chrome. So we wanted to know - pros and cons of using PhantomJS vs Selenium:</p>
<ul>
<li>Is there any real advantage in terms of performance, e.g. time taken to execute the test cases?</li>
<li>When should one prefer PhantomJS over Selenium?</li>
</ul> | 14,100,481 | 5 | 0 | null | 2012-12-31 09:24:41.433 UTC | 62 | 2019-03-12 10:38:40.113 UTC | 2017-03-22 11:46:29.49 UTC | null | 4,823,977 | null | 1,315,682 | null | 1 | 152 | google-chrome|user-interface|selenium|automation|phantomjs | 63,679 | <p>They are attacking different problems. Since PhantomJS runs perfectly on the command-line, it is suitable as the first layer of smoke testing, whether as part of development workflow and/or in a continuous integration server. Selenium targets multiple browsers and hence it is very useful to ensure cross-browser consistency and carry out extensive testings across different operating systems.</p>
<p>If your web application needs to run on a variety of web browsers, running the UI testing only with PhantomJS will not yield the most test coverage. However, it is perfectly fine to launch PhantomJS and exercise some basic sanity checks before doing the in-depth tests. Imagine the madness of testing a finance application where the login screen is unintentionally broken and non-functional!</p>
<p>Note that the line between the two gets slightly blurred with the recent WebDriver support in the latest PhantomJS. It is now possible to quickly run the tests first using PhantomJS and then (assuming there is no serious error encountered) continue to execute the same tests thoroughly in a Selenium setup.</p> |
19,812,988 | How to get a list of the grouped values in linq groupby? | <p>Linq newbie here, struggling with my first group by query.</p>
<p>I have a list of objects of type KeywordInstance which represent a keyword, and the ID of the database record to which the keyword was applied. </p>
<pre><code>Keyword RecordID
macrophages 1
macrophages 2
cell cycle 3
map kinase 2
cell cycle 1
</code></pre>
<p>What I want to have is a collection of all keywords, with a list of the RecordIDs to which each keyword was applied </p>
<pre><code>Keyword RecordIDs
macrophages 1, 2
cell cycle 1, 3
map kinase 2
</code></pre>
<p>I tried using Linq to get it into a new object. I only managed to get the distinct keywords. </p>
<p>var keywords = allWords
.GroupBy(w => w.keyword)
.Select(g => new {keyword = g.Key});</p>
<p>The problem is that I can't seem to get the values of g in any way. g is of the type IGrouping and by documentation, it only has the property Key, but not even the property Value. All the examples I have seen on the Internet for groupby just tell me to select g itself, but the result of </p>
<pre><code>var keywords = allWords
.GroupBy(w => w.keyword)
.Select(g => new {keyword = g.Key, RecordIDs = g});
</code></pre>
<p>is not what I want. </p>
<p><img src="https://i.stack.imgur.com/3rCNb.png" alt="screenshot of result"></p>
<p>Any try to get something out of g fails with the error message <code>System.Linq.IGropuing<string, UserQuery.KeywordInstance> does not have a definition for [whatever I tried]</code>. </p>
<p>What am I doing wrong here? </p> | 19,813,346 | 1 | 3 | null | 2013-11-06 13:10:57.803 UTC | 6 | 2013-11-06 13:27:29.493 UTC | null | null | null | null | 1,983,448 | null | 1 | 21 | linq|group-by | 41,525 | <p>I think you are close to you solution.</p>
<pre><code>var keywords = allWords
.GroupBy(w => w.keyword)
.Select(g => new
{
keyword = g.Key,
RecordIDs = g.Select(c => c.ID)
});
</code></pre>
<p>Just <code>Select</code> the records you need.<br/>
The reason you are seeing the <em>Keyword</em>-column as well as the <em>ID</em>-column, is becuase it's part of <code>g</code></p> |
24,651,489 | Asynctask vs Thread vs Services vs Loader | <p>I got slightly confused about the differences between <code>Asynctask</code>, <code>Thread</code>, <code>Service</code>, <code>Loader</code> in Android. </p>
<p>I know how it works. But i still don't understand what and when should i use.</p>
<p>I work with Android for 3 years, and generally still use <code>AsyncTask</code> for all background tasks (and sometimes Thread). But many people say that "Asynctask is outdated", and don't recommend to use them. Also they recommend to use robospice or Volley.</p>
<p>So, is <code>AsyncTask</code> really so bad and i should use framework for networking tasks? And what should i use for background (not networking) task?</p> | 24,652,931 | 6 | 2 | null | 2014-07-09 10:40:08.133 UTC | 17 | 2018-08-17 07:01:51.883 UTC | 2017-09-13 10:51:52.873 UTC | null | 4,999,394 | null | 1,991,579 | null | 1 | 32 | android|multithreading|android-asynctask|android-service | 18,347 | <p>AysncTasks are not 'outdated' as much as they are <strong>incomplete</strong>.
Among other things async tasks do not bother if their parent activity is currently running or not. For the same reason why you include checks for verify the context to be null or not. Besides, unless you are using your own Thread Pool Executor these tasks execute serially.</p>
<p>Volley tries to fill in those gaps, mainly concerning syncing up with the main thread and thread pooling. It behaves optimal if you wish to do stuff that requires average network requests; like some meta data list and images(picture the youtube app requests and facebook app requests for posts).</p>
<p>Typically few advantages of Volley are as follows</p>
<ol>
<li>It keeps the worker thread informed about the activity(Main thread)</li>
<li>Easier resource prioritization you could provide priority to your download requests.
A typical scenario would involve you giving priority to text over image.</li>
<li>Effective request cache and memory management.</li>
<li>Extensible</li>
<li>It provides you an option to discard your request in-case your activity was shutdown or restarted.</li>
<li>Simpler patterns for data retrieval as opposed to AsyncTasks.</li>
</ol>
<p>Volley fares badly when it comes to streaming requests/video as mentioned at Google I/O.</p>
<p>I'm not exactly aware of robospice.
Ps: If you have time on your hand see <a href="https://www.youtube.com/watch?v=yhv8l9F44qo" rel="nofollow noreferrer">https://www.youtube.com/watch?v=yhv8l9F44qo</a> </p>
<p>Here's a further read if you wish to go into other libraries with benchmarks for the same.
<a href="https://stackoverflow.com/questions/16902716/comparison-of-android-networking-libraries-okhttp-retrofit-volley/18863395#18863395">Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley</a></p> |
24,838,629 | round off float to nearest 0.5 in python | <p>I'm trying to round off floating digits to the nearest 0.5</p>
<p>For eg.</p>
<pre><code>1.3 -> 1.5
2.6 -> 2.5
3.0 -> 3.0
4.1 -> 4.0
</code></pre>
<p>This is what I'm doing</p>
<pre><code>def round_of_rating(number):
return round((number * 2) / 2)
</code></pre>
<p>This rounds of numbers to closest integer. What would be the correct way to do this?</p> | 24,838,652 | 1 | 2 | null | 2014-07-19 09:02:04.677 UTC | 5 | 2021-09-17 07:44:45.883 UTC | 2014-07-19 09:38:04.237 UTC | null | 20,670 | null | 3,136,225 | null | 1 | 59 | python | 65,247 | <p>Try to change the parenthesis position so that the rounding happens before the division by 2</p>
<pre><code>def round_off_rating(number):
"""Round a number to the closest half integer.
>>> round_off_rating(1.3)
1.5
>>> round_off_rating(2.6)
2.5
>>> round_off_rating(3.0)
3.0
>>> round_off_rating(4.1)
4.0"""
return round(number * 2) / 2
</code></pre>
<p><em>Edit:</em> Added a <a href="https://docs.python.org/2/library/doctest.html" rel="noreferrer"><code>doctest</code></a>able docstring:</p>
<pre><code>>>> import doctest
>>> doctest.testmod()
TestResults(failed=0, attempted=4)
</code></pre> |
490,439 | django-cart or Satchmo? | <p>I'm looking to implement a very basic shopping cart. <a href="http://www.satchmoproject.com/" rel="nofollow noreferrer">Satchmo</a> seems to install a <strong>lot</strong> of applications and extra stuff that I don't need. I've heard others mention <a href="http://code.google.com/p/django-cart/" rel="nofollow noreferrer">django-cart</a>. Has anyone tried this Django app (django-cart)? Anything to watch for or any other experiences?</p> | 490,534 | 6 | 0 | null | 2009-01-29 04:00:49.027 UTC | 13 | 2013-06-11 09:52:09 UTC | 2013-06-11 09:52:09 UTC | null | 70,211 | Ryan Duffield | 2,696 | null | 1 | 23 | python|django|e-commerce|satchmo | 12,849 | <p>Well if you want to use django-cart you should view it as a starting point for developing your own. The last commit (r4) for the project was November 2006.</p>
<p>By comparison, the last commit (r1922) to Satchmo was a couple of hours ago.</p>
<p>With Satchmo you get code that is under active development and actually used by real e-commerce sites.</p>
<p>If you develop your own you're running the risk of alienating customers and losing money. If you use Satchmo you can spend more time developing/improving other areas of your site.</p>
<p>I bet you can already guess my recommendation :)</p>
<p>As for the apps and other stuff in Satchmo I can tell you, from personal experience, that you don't need to include them all in your INSTALLED_APPS setting. I don't remember exactly what I pared it down to, but there were only around 6-7 Satchmo apps in my INSTALLED_APPS and they were all ones I needed. I think they've done even more modularization since then.</p> |
632,475 | Regex to pick characters outside of pair of quotes | <p>I would like to find a regex that will pick out all commas that fall outside quote sets. </p>
<p>For example:</p>
<pre><code>'foo' => 'bar',
'foofoo' => 'bar,bar'
</code></pre>
<p>This would pick out the single comma on line 1, after <code>'bar',</code></p>
<p>I don't really care about single vs double quotes.</p>
<p>Has anyone got any thoughts? I feel like this should be possible with readaheads, but my regex fu is too weak. </p> | 632,552 | 6 | 2 | null | 2009-03-10 22:09:41.397 UTC | 28 | 2020-05-31 19:34:37.41 UTC | 2020-05-31 19:34:37.41 UTC | null | 792,066 | SocialCensus | 26,001 | null | 1 | 42 | regex | 34,369 | <p>This will match any string up to and including the first non-quoted ",". Is that what you are wanting?</p>
<pre><code>/^([^"]|"[^"]*")*?(,)/
</code></pre>
<p>If you want all of them (and as a counter-example to the guy who said it wasn't possible) you could write:</p>
<pre><code>/(,)(?=(?:[^"]|"[^"]*")*$)/
</code></pre>
<p>which will match all of them. Thus</p>
<pre><code>'test, a "comma,", bob, ",sam,",here'.gsub(/(,)(?=(?:[^"]|"[^"]*")*$)/,';')
</code></pre>
<p>replaces all the commas <em>not</em> inside quotes with semicolons, and produces: </p>
<pre><code>'test; a "comma,"; bob; ",sam,";here'
</code></pre>
<p>If you need it to work across line breaks just add the m (multiline) flag.</p> |
785,226 | Practical use of `stackalloc` keyword | <p>Has anyone ever actually used <code>stackalloc</code> while programming in C#? I am aware of what is does, but the only time it shows up in my code is by accident, because Intellisense suggests it when I start typing <code>static</code>, for example.</p>
<p>Although it is not related to the usage scenarios of <code>stackalloc</code>, I actually do a considerable amount of legacy interop in my apps, so every now and then I could resort to using <code>unsafe</code> code. But nevertheless I usually find ways to avoid <code>unsafe</code> completely.</p>
<p>And since stack size for a single thread in .Net is ~1Mb (correct me if I'm wrong), I am even more reserved from using <code>stackalloc</code>.</p>
<p>Are there some practical cases where one could say: "this is exactly the right amount of data and processing for me to go unsafe and use <code>stackalloc</code>"?</p> | 785,264 | 6 | 1 | null | 2009-04-24 09:51:30.78 UTC | 36 | 2022-03-25 15:04:07.067 UTC | 2010-08-16 15:40:26.117 UTC | null | 1,288 | null | 69,809 | null | 1 | 176 | c#|keyword|stackalloc | 37,672 | <p>The sole reason to use <code>stackalloc</code> is performance (either for computations or interop). By using <code>stackalloc</code> instead of a heap allocated array, you create less GC pressure (the GC needs to run less), you don't need to pin the arrays down, it's faster to allocate than a heap array, an it is automatically freed on method exit (heap allocated arrays are only deallocated when GC runs). Also by using <code>stackalloc</code> instead of a native allocator (like malloc or the .Net equivalent) you also gain speed and automatic deallocation on scope exit.</p>
<p>Performance wise, if you use <code>stackalloc</code> you greatly increase the chance of cache hits on the CPU due to the locality of data.</p> |
35,471,894 | Can I run Jupyter notebook cells in commandline? | <p>I am deploying a Python package, and I would like to run a simple test to see if all cells in my notebook will run without errors. I would like to test this via commandline as I have issues running a notebook in <code>virtualenv</code>. Is there are simple command-line way to test this?</p>
<hr>
<p>Note to the moderator: this question has been marked as a duplicate of <a href="https://stackoverflow.com/questions/35545402/how-to-run-an-ipynb-jupyter-notebook-from-terminal">How to run an .ipynb Jupyter Notebook from terminal?
</a>. However, this question was posted (asked Feb 18 '16 at 2:49) several days before that one (asked Feb 22 '16 at 3:35). At most, that post might be marked as a duplicate, and if deemed so, an appropriate action would be to <a href="https://meta.stackoverflow.com/a/309004/4531270">merge the two questions, maintaining this, the original, as the master</a>. </p>
<p>However, these questions <em>may not</em> be duplicates (the intent of the other author is unclear). Regardless, this question and it's answers specifically address <strong>executing cells within a jupyter notebook from the terminal</strong>, not simply converting notebooks to python files. </p> | 35,472,438 | 4 | 3 | null | 2016-02-18 02:49:21.697 UTC | 19 | 2022-09-21 07:00:36.85 UTC | 2017-12-12 17:28:41.3 UTC | null | 4,531,270 | null | 4,531,270 | null | 1 | 73 | python|command-line|ipython|jupyter | 61,711 | <p>You can use <a href="https://github.com/paulgb/runipy" rel="noreferrer">runipy</a> to do this.</p>
<p><code>runipy</code> will run all cells in a notebook. If an error occurs, the process will stop.</p>
<blockquote>
<p><code>$ pip install runipy</code></p>
<p><code>$ runipy MyNotebook.ipynb</code></p>
</blockquote>
<p>There are also commands for saving the output file as a notebook or an html report:</p>
<blockquote>
<p><code>$ runipy MyNotebook.ipynb OutputNotebook.ipynb</code></p>
<p><code>$ runipy MyNotebook.ipynb --html report.html</code></p>
</blockquote> |
21,317,384 | How to concatenate two dataframes without duplicates? | <p>I'd like to concatenate two dataframes <code>A</code>, <code>B</code> to a new one without duplicate rows (if rows in <code>B</code> already exist in <code>A</code>, don't add):</p>
<p>Dataframe <code>A</code>:</p>
<pre><code> I II
0 1 2
1 3 1
</code></pre>
<p>Dataframe <code>B</code>:</p>
<pre><code> I II
0 5 6
1 3 1
</code></pre>
<p>New Dataframe:</p>
<pre><code> I II
0 1 2
1 3 1
2 5 6
</code></pre>
<p>How can I do this?</p> | 21,317,570 | 3 | 5 | null | 2014-01-23 19:16:45.653 UTC | 29 | 2022-05-09 15:19:39.837 UTC | 2022-05-09 15:19:39.837 UTC | null | 18,145,256 | null | 2,961,929 | null | 1 | 95 | python|pandas|duplicates | 143,580 | <p>The simplest way is to just do the concatenation, and then drop duplicates.</p>
<pre><code>>>> df1
A B
0 1 2
1 3 1
>>> df2
A B
0 5 6
1 3 1
>>> pandas.concat([df1,df2]).drop_duplicates().reset_index(drop=True)
A B
0 1 2
1 3 1
2 5 6
</code></pre>
<p>The <code>reset_index(drop=True)</code> is to fix up the index after the <code>concat()</code> and <code>drop_duplicates()</code>. Without it you will have an index of <code>[0,1,0]</code> instead of <code>[0,1,2]</code>. This could cause problems for further operations on this <code>dataframe</code> down the road if it isn't reset right away.</p> |
46,684,972 | Jenkins throws java.lang.IllegalArgumentException: Invalid refspec refs/heads/** Error | <p>I am trying to activate a pipeline on any merge request change. This works as long as my pipeline script is in <code>Jenkins UI</code>. Now I outsourced my script on <code>GitLab</code>, and the checkout should happen via the pipeline via scm option.</p>
<p>But all I get on build (yes, it triggers) is:</p>
<blockquote>
<p>java.lang.IllegalArgumentException: Invalid refspec refs/heads/**</p>
</blockquote>
<p>This happens if I leave the branch specifier empty, this is because I want to listen to any change. If I specify the branch, the build goes through.</p>
<p>My refspec:</p>
<pre><code>+refs/heads/*:refs/remotes/origin/* +refs/merge-requests/*/head:refs/remotes/origin/merge-requests/*
</code></pre> | 58,348,530 | 1 | 4 | null | 2017-10-11 09:45:35.417 UTC | 1 | 2019-10-11 21:14:33.893 UTC | 2017-11-22 23:35:54.487 UTC | null | 2,777,965 | null | 8,439,926 | null | 1 | 36 | jenkins|jenkins-pipeline | 13,169 | <p>Most likely this is a Jenkins bug. <a href="https://issues.jenkins-ci.org/browse/JENKINS-46588" rel="noreferrer">https://issues.jenkins-ci.org/browse/JENKINS-46588</a>
There seems to a solution anyway:</p>
<p>In your project configuration under Pipeline -> SCM -> Branches to build -> "Branch Specifier (blank for 'any'):
Do not use blank for any or * or .* or **. Use:</p>
<pre><code>*/*
</code></pre>
<p>Another workaround would be to disable Lightweight Checkout.</p>
<p>PS:
Big thanks to ChrisAnnODell and Omurbek Kadyrbekov for linking the solutions in first place.
I'm still a bit puzzled that there is no fix for over 2 years now...</p> |
46,706,433 | Firebase Firestore get data from collection | <p>I want to get data from my Firebase Firestore database. I have a collection called user and every user has collection of some objects of the same type (My Java custom object). I want to fill my ArrayList with these objects when my Activity is created. </p>
<pre><code>private static ArrayList<Type> mArrayList = new ArrayList<>();;
</code></pre>
<p>In onCreate():</p>
<pre><code>getListItems();
Log.d(TAG, "onCreate: LIST IN ONCREATE = " + mArrayList);
*// it logs empty list here
</code></pre>
<p>Method called to get items to list:</p>
<pre><code>private void getListItems() {
mFirebaseFirestore.collection("some collection").get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot documentSnapshots) {
if (documentSnapshots.isEmpty()) {
Log.d(TAG, "onSuccess: LIST EMPTY");
return;
} else {
for (DocumentSnapshot documentSnapshot : documentSnapshots) {
if (documentSnapshot.exists()) {
Log.d(TAG, "onSuccess: DOCUMENT" + documentSnapshot.getId() + " ; " + documentSnapshot.getData());
DocumentReference documentReference1 = FirebaseFirestore.getInstance().document("some path");
documentReference1.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
Type type= documentSnapshot.toObject(Type.class);
Log.d(TAG, "onSuccess: " + type.toString());
mArrayList.add(type);
Log.d(TAG, "onSuccess: " + mArrayList);
/* these logs here display correct data but when
I log it in onCreate() method it's empty*/
}
});
}
}
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Error getting data!!!", Toast.LENGTH_LONG).show();
}
});
}
</code></pre> | 46,714,740 | 5 | 6 | null | 2017-10-12 09:47:03.13 UTC | 4 | 2020-10-01 03:07:39.247 UTC | 2017-10-14 03:12:33.55 UTC | null | 209,103 | null | 1,830,590 | null | 1 | 14 | java|android|arraylist|google-cloud-firestore | 99,535 | <p>The <code>get()</code> operation returns a <code>Task<></code> which means it is an <strong>asynchronous operation</strong>. Calling <code>getListItems()</code> only starts the operation, it does not wait for it to complete, that's why you have to add success and failure listeners.</p>
<p>Although there's not much you can do about the async nature of the operation, you can simplify your code as follows:</p>
<pre><code>private void getListItems() {
mFirebaseFirestore.collection("some collection").get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot documentSnapshots) {
if (documentSnapshots.isEmpty()) {
Log.d(TAG, "onSuccess: LIST EMPTY");
return;
} else {
// Convert the whole Query Snapshot to a list
// of objects directly! No need to fetch each
// document.
List<Type> types = documentSnapshots.toObjects(Type.class);
// Add all to your list
mArrayList.addAll(types);
Log.d(TAG, "onSuccess: " + mArrayList);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Error getting data!!!", Toast.LENGTH_LONG).show();
}
});
}
</code></pre> |
33,383,840 | Is there a JavaScript equivalent of the Python pass statement that does nothing? | <p>I am looking for a JavaScript equivalent of the Python:</p>
<p><code>pass</code> statement that does not run the function of the <code>...</code> notation?</p>
<p><strong>Is there such a thing in JavaScript?</strong></p> | 33,383,865 | 10 | 4 | null | 2015-10-28 05:53:58.833 UTC | 10 | 2021-09-27 20:57:50.753 UTC | 2020-12-09 08:40:20.427 UTC | null | 13,903,942 | null | 1,709,088 | null | 1 | 144 | javascript|python|function|lexical | 116,744 | <p>Python's <code>pass</code> mainly exists because in Python whitespace matters within a block. In Javascript, the equivalent would be putting nothing within the block, i.e. <code>{}</code>.</p> |
1,670,138 | PHP IF statement for Boolean values: $var === true vs $var | <p>I know this question is not really important.. however I've been wondering:</p>
<p>Which of the following IF statements is the best and fastest to use?</p>
<pre><code><?php
$variable = true;
if($variable === true)
{
//Something
}
if($variable)
{
// Something
}
?>
</code></pre>
<p>I know === is to match exactly the boolean value. However is there really any improvement?</p> | 1,670,150 | 5 | 2 | null | 2009-11-03 21:07:29.81 UTC | 4 | 2012-01-11 15:55:03.893 UTC | null | null | null | null | 140,901 | null | 1 | 32 | php|coding-style|paradigms | 107,864 | <p>Using <code>if ($var === true)</code> or <code>if ($var)</code> is not a question of style but a question of correctness. Because <code>if ($var)</code> is the same as <code>if ($var == true)</code>. And <code>==</code> comparison doesn’t check the type. So <code>1 == true</code> is true but <code>1 === true</code> is false.</p> |
2,231,163 | what tomcat native library should I be using in production? | <p>When I compile my spring mvc app, I get this in the output:</p>
<pre><code>INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.6.0_17\bin;......
</code></pre>
<p>What exactly should I use in production that this is referring to?</p> | 2,231,186 | 6 | 0 | null | 2010-02-09 17:45:05.34 UTC | 7 | 2018-05-09 10:59:57.5 UTC | null | null | null | null | 39,677 | null | 1 | 20 | java|spring|spring-mvc | 49,631 | <p><a href="http://tomcat.apache.org/native-doc/" rel="noreferrer">Tomcat-native</a> is a version of Tomcat that uses the highly optimized Apache Portable Runtime (APR), the same framework that powers the Apache HTTP server.</p> |
1,636,194 | Flexible CountDownLatch? | <p>I have encountered a problem twice now whereby a producer thread produces N work items, submits them to an <code>ExecutorService</code> and then needs to wait until all N items have been processed.</p>
<p><strong>Caveats</strong></p>
<ul>
<li><strong>N is not known in advance</strong>. If it were I would simply create a <code>CountDownLatch</code> and then have producer thread <code>await()</code> until all work was complete.</li>
<li>Using a <code>CompletionService</code> is inappropriate because although my producer thread needs to block (i.e. by calling <code>take()</code>) there's <strong>no way of signalling that all work is complete</strong>, to cause the producer thread to stop waiting.</li>
</ul>
<p>My current favoured solution is to use an integer counter, and to <strong>increment</strong> this whenever an item of work is submitted and to <strong>decrement</strong> it when a work item is processed. Following the subsmission of all N tasks my producer thread will need to wait on a lock, checking whether <code>counter == 0</code> whenever it is notified. The consumer thread(s) will need to notify the producer if it has decremented the counter and the new value is 0.</p>
<p>Is there a better approach to this problem or is there a suitable construct in <code>java.util.concurrent</code> I should be using rather than "rolling my own"?</p>
<p>Thanks in advance.</p> | 1,637,030 | 6 | 3 | null | 2009-10-28 09:52:16.573 UTC | 12 | 2018-08-08 11:58:33.987 UTC | 2017-05-18 16:35:37.943 UTC | null | 4,999,394 | null | 127,479 | null | 1 | 28 | java|multithreading|concurrency|countdownlatch|phaser | 9,461 | <p><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html" rel="noreferrer"><code>java.util.concurrent.Phaser</code></a> looks like it would work well for you. It is planned to be release in Java 7 but the most stable version can be found at <a href="http://gee.cs.oswego.edu/dl/concurrency-interest/index.html" rel="noreferrer">jsr166</a>'s interest group website.</p>
<p>The phaser is a glorified Cyclic Barrier. You can register N number of parties and when youre ready await their advance at the specific phase.</p>
<p>A quick example on how it would work:</p>
<pre><code>final Phaser phaser = new Phaser();
public Runnable getRunnable(){
return new Runnable(){
public void run(){
..do stuff...
phaser.arriveAndDeregister();
}
};
}
public void doWork(){
phaser.register();//register self
for(int i=0 ; i < N; i++){
phaser.register(); // register this task prior to execution
executor.submit( getRunnable());
}
phaser.arriveAndAwaitAdvance();
}
</code></pre> |
2,321,829 | Android AsyncTask testing with Android Test Framework | <p>I have a very simple AsyncTask implementation example and am having problem in testing it using Android JUnit framework. </p>
<p>It works just fine when I instantiate and execute it in normal application.
However when it's executed from any of Android Testing framework classes (i.e. <strong><em>AndroidTestCase</em></strong>, <strong><em>ActivityUnitTestCase</em></strong>, <strong><em>ActivityInstrumentationTestCase2</em></strong> etc) it behaves strangely: </p>
<ul>
<li>It executes <code>doInBackground()</code> method correctly </li>
<li>However it doesn't invokes any of its notification methods (<code>onPostExecute()</code>, <code>onProgressUpdate()</code>, etc) -- just silently ignores them without showing any errors.</li>
</ul>
<p>This is very simple AsyncTask example:</p>
<pre><code>package kroz.andcookbook.threads.asynctask;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.Toast;
public class AsyncTaskDemo extends AsyncTask<Integer, Integer, String> {
AsyncTaskDemoActivity _parentActivity;
int _counter;
int _maxCount;
public AsyncTaskDemo(AsyncTaskDemoActivity asyncTaskDemoActivity) {
_parentActivity = asyncTaskDemoActivity;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
_parentActivity._progressBar.setVisibility(ProgressBar.VISIBLE);
_parentActivity._progressBar.invalidate();
}
@Override
protected String doInBackground(Integer... params) {
_maxCount = params[0];
for (_counter = 0; _counter <= _maxCount; _counter++) {
try {
Thread.sleep(1000);
publishProgress(_counter);
} catch (InterruptedException e) {
// Ignore
}
}
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
int progress = values[0];
String progressStr = "Counting " + progress + " out of " + _maxCount;
_parentActivity._textView.setText(progressStr);
_parentActivity._textView.invalidate();
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
_parentActivity._progressBar.setVisibility(ProgressBar.INVISIBLE);
_parentActivity._progressBar.invalidate();
}
@Override
protected void onCancelled() {
super.onCancelled();
_parentActivity._textView.setText("Request to cancel AsyncTask");
}
}
</code></pre>
<p>This is a test case. Here <em>AsyncTaskDemoActivity</em> is a very simple Activity providing UI for testing AsyncTask in mode:</p>
<pre><code>package kroz.andcookbook.test.threads.asynctask;
import java.util.concurrent.ExecutionException;
import kroz.andcookbook.R;
import kroz.andcookbook.threads.asynctask.AsyncTaskDemo;
import kroz.andcookbook.threads.asynctask.AsyncTaskDemoActivity;
import android.content.Intent;
import android.test.ActivityUnitTestCase;
import android.widget.Button;
public class AsyncTaskDemoTest2 extends ActivityUnitTestCase<AsyncTaskDemoActivity> {
AsyncTaskDemo _atask;
private Intent _startIntent;
public AsyncTaskDemoTest2() {
super(AsyncTaskDemoActivity.class);
}
protected void setUp() throws Exception {
super.setUp();
_startIntent = new Intent(Intent.ACTION_MAIN);
}
protected void tearDown() throws Exception {
super.tearDown();
}
public final void testExecute() {
startActivity(_startIntent, null, null);
Button btnStart = (Button) getActivity().findViewById(R.id.Button01);
btnStart.performClick();
assertNotNull(getActivity());
}
}
</code></pre>
<p>All this code is working just fine, except the fact that AsyncTask doesn't invoke it's notification methods when executed by within Android Testing Framework. Any ideas?</p> | 3,802,487 | 8 | 0 | null | 2010-02-23 21:22:39.067 UTC | 56 | 2022-03-15 20:04:24.883 UTC | 2018-01-15 07:54:53.327 UTC | null | 3,058,050 | null | 209,310 | null | 1 | 99 | android|junit | 61,441 | <p>I met a similar problem while implementing some unit-test. I had to test some service which worked with Executors, and I needed to have my service callbacks sync-ed with the test methods from my ApplicationTestCase classes. Usually the test method itself finished before the callback would be accessed, so the data sent via the callbacks would not be tested. Tried applying the @UiThreadTest bust still didn't work.</p>
<p>I found the following method, which worked, and I still use it. I simply use CountDownLatch signal objects to implement the wait-notify (you can use synchronized(lock){... lock.notify();}, however this results in ugly code) mechanism.</p>
<pre><code>public void testSomething(){
final CountDownLatch signal = new CountDownLatch(1);
Service.doSomething(new Callback() {
@Override
public void onResponse(){
// test response data
// assertEquals(..
// assertTrue(..
// etc
signal.countDown();// notify the count down latch
}
});
signal.await();// wait for callback
}
</code></pre> |
Subsets and Splits