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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
60,174 | How can I prevent SQL injection in PHP? | <p>If user input is inserted without modification into an SQL query, then the application becomes vulnerable to <a href="https://stackoverflow.com/a/332367/">SQL injection</a>, like in the following example:</p>
<pre class="lang-php prettyprint-override"><code>$unsafe_variable = $_POST['user_input'];
mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')");
</code></pre>
<p>That's because the user can input something like <code>value'); DROP TABLE table;--</code>, and the query becomes:</p>
<pre><code>INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')
</code></pre>
<p>What can be done to prevent this from happening?</p> | 60,496 | 28 | 0 | 2012-11-05 16:18:49.497 UTC | 2008-09-12 23:55:00.9 UTC | 3,804 | 2022-09-01 14:26:49.707 UTC | 2016-10-01 08:08:27.57 UTC | user456814 | 707,111 | Andrew G. Johnson | 428,190 | null | 1 | 2,773 | php|mysql|sql|security|sql-injection | 2,063,980 | <p>The <em>correct</em> way to avoid SQL injection attacks, no matter which database you use, is to <strong>separate the data from SQL</strong>, so that data stays data and will <strong>never be interpreted</strong> as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don't <em>fully</em> understand the details, you should always <strong>use prepared statements and parameterized queries.</strong> These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.</p>
<p>You basically have two options to achieve this:</p>
<ol>
<li><p>Using <a href="http://php.net/manual/en/book.pdo.php" rel="noreferrer"><strong>PDO</strong></a> (for any supported database driver):</p>
<pre class="lang-php prettyprint-override"><code>$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute([ 'name' => $name ]);
foreach ($stmt as $row) {
// Do something with $row
}
</code></pre>
</li>
<li><p>Using <a href="http://php.net/manual/en/book.mysqli.php" rel="noreferrer"><strong>MySQLi</strong></a> (for MySQL):</p>
<pre class="lang-php prettyprint-override"><code>$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Do something with $row
}
</code></pre>
</li>
</ol>
<p>If you're connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, <code>pg_prepare()</code> and <code>pg_execute()</code> for PostgreSQL). PDO is the universal option.</p>
<hr />
<h2>Correctly setting up the connection</h2>
<h4>PDO</h4>
<p>Note that when using <strong>PDO</strong> to access a MySQL database <em>real</em> prepared statements are <strong>not used by default</strong>. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using <strong>PDO</strong> is:</p>
<pre class="lang-php prettyprint-override"><code>$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4', 'user', 'password');
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
</code></pre>
<p>In the above example, the error mode isn't strictly necessary, <strong>but it is advised to add it</strong>. This way PDO will inform you of all MySQL errors by means of throwing the <code>PDOException</code>.</p>
<p>What is <strong>mandatory</strong>, however, is the first <code>setAttribute()</code> line, which tells PDO to disable emulated prepared statements and use <em>real</em> prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).</p>
<p>Although you can set the <code>charset</code> in the options of the constructor, it's important to note that 'older' versions of PHP (before 5.3.6) <a href="http://php.net/manual/en/ref.pdo-mysql.connection.php" rel="noreferrer">silently ignored the charset parameter</a> in the DSN.</p>
<h4>Mysqli</h4>
<p>For mysqli we have to follow the same routine:</p>
<pre class="lang-php prettyprint-override"><code>mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // error reporting
$dbConnection = new mysqli('127.0.0.1', 'username', 'password', 'test');
$dbConnection->set_charset('utf8mb4'); // charset
</code></pre>
<hr />
<h2>Explanation</h2>
<p>The SQL statement you pass to <code>prepare</code> is parsed and compiled by the database server. By specifying parameters (either a <code>?</code> or a named parameter like <code>:name</code> in the example above) you tell the database engine where you want to filter on. Then when you call <code>execute</code>, the prepared statement is combined with the parameter values you specify.</p>
<p>The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn't intend.</p>
<p>Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the <code>$name</code> variable contains <code>'Sarah'; DELETE FROM employees</code> the result would simply be a search for the string <code>"'Sarah'; DELETE FROM employees"</code>, and you will not end up with <a href="http://xkcd.com/327/" rel="noreferrer">an empty table</a>.</p>
<p>Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.</p>
<p>Oh, and since you asked about how to do it for an insert, here's an example (using PDO):</p>
<pre class="lang-php prettyprint-override"><code>$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');
$preparedStatement->execute([ 'column' => $unsafeValue ]);
</code></pre>
<hr />
<h2>Can prepared statements be used for dynamic queries?</h2>
<p>While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.</p>
<p>For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.</p>
<pre><code>// Value whitelist
// $dir can only be 'DESC', otherwise it will be 'ASC'
if (empty($dir) || $dir !== 'DESC') {
$dir = 'ASC';
}
</code></pre> |
34,586,109 | Check two arguments in Java, either both not null or both null elegantly | <p>I used spring boot to develop a shell project used to send email, e.g.</p>
<pre><code>sendmail -from [email protected] -password foobar -subject "hello world" -to [email protected]
</code></pre>
<p>If the <code>from</code> and <code>password</code> arguments are missing, I use a default sender and password, e.g. <code>[email protected]</code> and <code>123456</code>.</p>
<p>So if the user passes the <code>from</code> argument they must also pass the <code>password</code> argument and vice versa. That is to say, either both are non-null, or both are null.</p>
<p>How do I check this elegantly?</p>
<p>Now my way is</p>
<pre><code>if ((from != null && password == null) || (from == null && password != null)) {
throw new RuntimeException("from and password either both exist or both not exist");
}
</code></pre> | 34,586,232 | 14 | 8 | null | 2016-01-04 06:57:24.323 UTC | 20 | 2022-08-11 18:44:35.657 UTC | 2016-01-08 17:06:28.723 UTC | null | 1,267,663 | null | 4,428,471 | null | 1 | 172 | java | 41,831 | <p>There is a way using the <code>^</code> (<a href="https://en.wikipedia.org/wiki/Exclusive_or" rel="noreferrer">XOR</a>) operator:</p>
<pre><code>if (from == null ^ password == null) {
// Use RuntimeException if you need to
throw new IllegalArgumentException("message");
}
</code></pre>
<p>The <code>if</code> condition will be true if only one variable is null.</p>
<p>But I think usually it's better to use two <code>if</code> conditions with different exception messages. You can't define what went wrong using a single condition.</p>
<pre><code>if ((from == null) && (password != null)) {
throw new IllegalArgumentException("If from is null, password must be null");
}
if ((from != null) && (password == null)) {
throw new IllegalArgumentException("If from is not null, password must not be null");
}
</code></pre>
<p>It is more readable and is much easier to understand, and it only takes a little extra typing.</p> |
6,870,148 | Is there a Haskell code formatter? | <p>I used to write</p>
<pre><code>data A = A {
a :: Double
}
deriving(Eq, Show)
</code></pre>
<p>but now i prefer</p>
<pre><code>data A = A {
a :: Double
} deriving(Eq, Show)
</code></pre>
<p>I think the answer will be no, but i ask anyway: is there a code formatter for Haskell?</p> | 6,870,747 | 4 | 2 | null | 2011-07-29 07:54:09.183 UTC | 16 | 2015-02-06 11:54:10.983 UTC | null | null | null | null | 437,866 | null | 1 | 44 | haskell|code-formatting | 10,993 | <h1>New answer</h1>
<p>I have now written <a href="http://hackage.haskell.org/package/hindent" rel="noreferrer">hindent</a>, which is written in terms of <a href="http://hackage.haskell.org/package/haskell-src-exts" rel="noreferrer">haskell-src-exts</a>. It has Emacs and Vim support.</p>
<hr>
<h1>Old answer</h1>
<p>There is <a href="http://hackage.haskell.org/package/haskell-src-exts" rel="noreferrer">haskell-src-exts</a> which will parse your code and it has a pretty printing module for printing the AST to a string. E.g.</p>
<pre><code>import Language.Haskell.Exts
main = interact codeFormat
codeFormat = check . fmap reformat . parseModuleWithComments where
reformat = prettyPrint
check r = case r of
ParseOk a -> a
ParseFailed loc err -> error $ show (loc,err)
</code></pre>
<p>Example:</p>
<pre><code>λ> putStrLn $ codeFormat "module X where x = 1 where { y 1 = 2; y _ = 2 }"
module X where
x = 1
where y 1 = 2
y _ = 2
</code></pre>
<p>Alternatively you can write a pretty printer yourself (even based on the above if you just want to specialise), and then you can have whatever style you want. Replace <code>prettyPrint</code> with your own. The AST is very straight-forward.</p>
<p>Then you can hook it up with Emacs to reformat every time you hit save or something.</p> |
6,862,813 | C -- passing a 2d array as a function argument? | <p>One can easily define a function that accepts a <code>1d array</code> argument like this:</p>
<pre><code>int MyFunction( const float arr[] )
{
// do something here, then return...
return 1
}
</code></pre>
<p>Although a definition such as:
<code>int MyFunction( const float* arr )</code> would work as well.</p>
<p>How can one define a function that accepts a <code>2d array</code> argument? </p>
<p>I know that this works:
<code>int MyFunction( const float** arr )</code> -- but, is it possible to use the first variation that uses <code>[]</code>?</p> | 6,862,954 | 5 | 5 | null | 2011-07-28 17:05:02.71 UTC | 8 | 2016-03-14 19:42:00.913 UTC | null | null | null | null | 540,009 | null | 1 | 12 | c | 73,699 | <p>In C99, you can provide the dimensions of the array before passing it:</p>
<pre><code> void array_function(int m, int n, float a[m][n])
{
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
a[i][j] = 0.0;
}
void another_function(void)
{
float a1[10][20];
float a2[15][15];
array_function(10, 20, a1);
array_function(15, 15, a2);
}
</code></pre> |
6,962,658 | Randomize setInterval ( How to rewrite same random after random interval) | <p>I'd like to know how to achieve:
generate a random number after a random number of time. And reuse it.</p>
<pre><code>function doSomething(){
// ... do something.....
}
var rand = 300; // initial rand time
i = setinterval(function(){
doSomething();
rand = Math.round(Math.random()*(3000-500))+500; // generate new time (between 3sec and 500"s)
}, rand);
</code></pre>
<p>And do it repeatedly.</p>
<p>So far I was able to generate a random interval, but it last the same until the page was refreshed (generating than a different time- interval).</p>
<p>Thanks</p> | 6,962,808 | 5 | 0 | null | 2011-08-05 21:06:49.003 UTC | 20 | 2020-09-27 10:38:07.58 UTC | 2011-08-09 03:19:46.977 UTC | null | 814,690 | null | 383,904 | null | 1 | 49 | javascript|jquery | 57,442 | <p>Here is a really clean and clear way to do it:</p>
<p><a href="http://jsfiddle.net/Akkuma/9GyyA/" rel="noreferrer">http://jsfiddle.net/Akkuma/9GyyA/</a></p>
<pre><code>function doSomething() {}
(function loop() {
var rand = Math.round(Math.random() * (3000 - 500)) + 500;
setTimeout(function() {
doSomething();
loop();
}, rand);
}());
</code></pre>
<p><strong>EDIT:</strong></p>
<p>Explanation:
loop only exists within the immediately invoked function context, so it can recursively call itself.</p> |
6,410,810 | Rails not decoding JSON from jQuery correctly (array becoming a hash with integer keys) | <p>Every time I want to POST an array of JSON objects with jQuery to Rails, I have this problem.
If I stringify the array I can see that jQuery is doing its work correctly:</p>
<pre><code>"shared_items"=>"[{\"entity_id\":\"253\",\"position\":1},{\"entity_id\":\"823\",\"position\":2}]"
</code></pre>
<p>But if I just send the array it as the data of the AJAX call I get:</p>
<pre><code>"shared_items"=>{"0"=>{"entity_id"=>"253", "position"=>"1"}, "1"=>{"entity_id"=>"823", "position"=>"2"}}
</code></pre>
<p>Whereas if I just send a plain array it works:</p>
<pre><code>"shared_items"=>["entity_253"]
</code></pre>
<p>Why is Rails changing the array to that strange hash? The only reason that comes to mind is that Rails can't correctly understand the contents because there is no type here (is there a way to set it in the jQuery call?):</p>
<pre><code>Processing by SharedListsController#create as
</code></pre>
<p>Thank you!</p>
<p><strong>Update:</strong>
I'm sending the data as an array, not a string and the array is created dynamically using the <code>.push()</code> function. Tried with <code>$.post</code> and <code>$.ajax</code>, same result.</p> | 11,697,679 | 7 | 0 | null | 2011-06-20 12:03:46.497 UTC | 32 | 2017-10-02 23:27:13.293 UTC | 2017-10-02 23:27:13.293 UTC | null | 2,252,927 | null | 419,656 | null | 1 | 92 | jquery|ruby-on-rails|arrays|json|post | 28,200 | <p>In case someone stumbles upon this and wants a better solution, you can specify the "contentType: 'application/json'" option in the .ajax call and have Rails properly parse the JSON object without garbling it into integer-keyed hashes with all-string values.</p>
<p>So, to summarize, my problem was that this:</p>
<pre><code>$.ajax({
type : "POST",
url : 'http://localhost:3001/plugin/bulk_import/',
dataType: 'json',
data : {"shared_items": [{"entity_id":"253","position":1}, {"entity_id":"823","position":2}]}
});
</code></pre>
<p>resulted in Rails parsing things as:</p>
<pre><code>Parameters: {"shared_items"=>{"0"=>{"entity_id"=>"253", "position"=>"1"}, "1"=>{"entity_id"=>"823", "position"=>"2"}}}
</code></pre>
<p>whereas this (NOTE: we're now stringifying the javascript object and specifying a content type, so rails will know how to parse our string):</p>
<pre><code>$.ajax({
type : "POST",
url : 'http://localhost:3001/plugin/bulk_import/',
dataType: 'json',
contentType: 'application/json',
data : JSON.stringify({"shared_items": [{"entity_id":"253","position":1}, {"entity_id":"823","position":2}]})
});
</code></pre>
<p>results in a nice object in Rails:</p>
<pre><code>Parameters: {"shared_items"=>[{"entity_id"=>"253", "position"=>1}, {"entity_id"=>"823", "position"=>2}]}
</code></pre>
<p>This works for me in Rails 3, on Ruby 1.9.3.</p> |
6,750,531 | Using a .php file to generate a MySQL dump | <p>Here's the information I have:</p>
<p>I am working with a Linux based system using MySQL and PHP5. I need to be able to generate a <code>mysqldump</code> from within a .php file, and then have that dump be stored in a file on the server in a location I would specify.</p>
<p>As I'm a PHP nooblet, I'd like someone to give me some assistance, guidance, or code, that would do what I require. This would have to be run remotely from the Internet.</p> | 6,750,595 | 13 | 4 | null | 2011-07-19 16:20:08.477 UTC | 58 | 2022-08-19 18:10:02.093 UTC | 2012-07-20 00:18:13.48 UTC | null | 367,456 | null | 603,346 | null | 1 | 133 | php|mysql|mysqldump | 239,782 | <p>You can use the <a href="http://www.php.net/manual/en/function.exec.php"><strong><code>exec()</code></strong></a> function to execute an external command.</p>
<p>Note: between <code>shell_exec()</code> and <code>exec()</code>, I would choose the second one, which doesn't return the output to the PHP script -- no need for the PHP script to get the whole SQL dump as a string : you only need it written to a file, and this can be done by the command itself.</p>
<p><br>
That external command will :</p>
<ul>
<li>be a call to <code>mysqldump</code>, with the right parameters, </li>
<li>and redirect the output to a file.</li>
</ul>
<p>For example :</p>
<pre><code>mysqldump --user=... --password=... --host=... DB_NAME > /path/to/output/file.sql
</code></pre>
<p><br>
Which means your PHP code would look like this :</p>
<pre><code>exec('mysqldump --user=... --password=... --host=... DB_NAME > /path/to/output/file.sql');
</code></pre>
<p><br>
<em>Of course, up to you to use the right connection information, replacing the <code>...</code> with those.</em></p> |
6,539,879 | How to convert a color integer to a hex String in Android? | <p>I have an integer that was generated from an <code>android.graphics.Color</code></p>
<p>The Integer has a value of -16776961</p>
<p>How do I convert this value into a hex string with the format #RRGGBB</p>
<p>Simply put: I would like to output #0000FF from -16776961</p>
<p><strong>Note:</strong> I do not want the output to contain an alpha and i have also tried <a href="https://stackoverflow.com/questions/4506708/android-convert-color-int-to-hexa-string">this example</a> without any success</p> | 6,540,378 | 13 | 4 | null | 2011-06-30 19:12:24.01 UTC | 52 | 2022-08-28 13:02:08.033 UTC | 2017-05-23 12:10:54.147 UTC | null | -1 | null | 777,976 | null | 1 | 229 | java|android|string|colors|hex | 130,406 | <p>The mask makes sure you only get RRGGBB, and the %06X gives you zero-padded hex (always 6 chars long):</p>
<pre><code>String hexColor = String.format("#%06X", (0xFFFFFF & intColor));
</code></pre> |
6,407,141 | How can I have ruby logger log output to stdout as well as file? | <p>Someting like a tee functionality in logger.</p> | 6,407,200 | 21 | 2 | null | 2011-06-20 05:30:16.273 UTC | 40 | 2021-06-27 21:30:50.87 UTC | null | null | null | null | 710,238 | null | 1 | 102 | ruby|logging | 56,741 | <p>You can write a pseudo <code>IO</code> class that will write to multiple <code>IO</code> objects. Something like:</p>
<pre><code>class MultiIO
def initialize(*targets)
@targets = targets
end
def write(*args)
@targets.each {|t| t.write(*args)}
end
def close
@targets.each(&:close)
end
end
</code></pre>
<p>Then set that as your log file:</p>
<pre><code>log_file = File.open("log/debug.log", "a")
Logger.new MultiIO.new(STDOUT, log_file)
</code></pre>
<p>Every time <code>Logger</code> calls <code>puts</code> on your <code>MultiIO</code> object, it will write to both <code>STDOUT</code> and your log file.</p>
<p><strong>Edit:</strong> I went ahead and figured out the rest of the interface. A log device must respond to <code>write</code> and <code>close</code> (not <code>puts</code>). As long as <code>MultiIO</code> responds to those and proxies them to the real IO objects, this should work.</p> |
38,247,907 | How to set the y range in boxplot graph? | <p>I'm using <code>boxplot()</code> in R. My code is:</p>
<pre><code>#rm(list=ls())
#B2
fps_error <- c(0.058404273, 0.028957446, 0.026276044, 0.07084294, 0.078438563, 0.024000178, 0.120678965, 0.081774358, 0.025644741, 0.02931614)
fps_error = fps_error *100
fps_qp_error <-c(1.833333333, 1.69047619, 1.666666667, 3.095238095, 2.738095238, 1.714285714, 3.634146341, 5.142857143, 1.238095238, 2.30952381)
bit_error <- c(0.141691737, 0.136173785, 0.073808209, 0.025057931, 0.165722097, 0.004276999, 0.365353752, 0.164757488, 0.003362543, 0.022423845)
bit_error = bit_error *100
bit_qp_error <-c(0.666666667, 0.785714286, 0.428571429, 0.142857143, 0.785714286, 0.023809524, 1.523809524, 0.976190476, 0.023809524, 0.142857143)
ssim_error <-c(0.01193773, 0.015151569, 0.003144532, 0.003182908, 0.008125274, 0.013796366, 0.00359078, 0.019002591, 0.005031524, 0.004370175)
ssim_error = ssim_error * 100
ssim_qp_error <-c(3.833333333, 1.80952381, 0.69047619, 0.571428571, 2, 1.904761905, 0.761904762, 2.119047619, 0.857142857, 0.976190476)
all_errors = cbind(fps_error, bit_error, ssim_error)
all_qp_errors = cbind(fps_qp_error, bit_qp_error, ssim_qp_error)
modes = cbind(rep("FPS error",10), rep("Bitrate error",10), rep("SSIM error",10))
journal_linear_data <-data.frame(fps_error, fps_qp_error,bit_error,bit_qp_error,ssim_error,ssim_qp_error )
yvars <- c("fps_error","bit_error","ssim_error")
yvars_qp <-c("fps_qp_error","bit_qp_error","ssim_qp_error")
xvars <- c("FPS", "Bitrate", "SSIM")
graphics.off()
bmp(filename="boxplot_B2_error.bmp")
op <- par(mfrow = c(1, 3), #matrix of plots
oma = c(0,0,2,0),mar=c(5.1, 7.1, 2.1, 2.1),mgp=c(4,1,0)) #outer margins
par(cex.lab=3)
par(cex.axis=3)
for (i in 1:3) {boxplot(journal_linear_data[,yvars[i]], xlab=xvars[i], ylab="Percentage error", outcex = 2)}
par(op)
mtext(text="Percentage error per mode for B2",side=3, line=1.5, font=2, cex=2,adj=0.95, col='black')
dev.off()
</code></pre>
<p>The image output is shown below. As you can see the y-axis does not have the same range for all graphs. How can I fix this? For example starting in 0.5 or 0. </p>
<p><a href="https://i.stack.imgur.com/quV92.png" rel="noreferrer"><img src="https://i.stack.imgur.com/quV92.png" alt="enter image description here"></a></p> | 38,248,033 | 1 | 2 | null | 2016-07-07 14:20:15.65 UTC | 1 | 2016-07-07 15:52:28.507 UTC | 2016-07-07 15:52:28.507 UTC | null | 4,891,738 | null | 1,395,874 | null | 1 | 14 | r|plot|boxplot | 69,247 | <p>You can simply put an <code>ylim = c(0, 5)</code> in all your <code>boxplot()</code> call. This sets y-axis range (roughly) between 0 and 5.</p>
<p>Perhaps you did not see <code>ylim</code> argument in <code>?boxplot</code>; the "Arguments" section also does not mention it. But <code>ylim</code> is just a trivial graphical parameter passed via "<code>...</code>". You can also find such example in the "Examples" session of <code>?boxplot</code>:</p>
<pre><code> boxplot(len ~ dose, data = ToothGrowth,
boxwex = 0.25, at = 1:3 - 0.2,
subset = supp == "VC", col = "yellow",
main = "Guinea Pigs' Tooth Growth",
xlab = "Vitamin C dose mg",
ylab = "tooth length",
xlim = c(0.5, 3.5), ylim = c(0, 35), yaxs = "i")
</code></pre> |
45,277,306 | Check if item exists in array React | <p>I'm trying to check if an item exists in my array <code>data</code> and if it does then prevent it from being added to the array.</p>
<p>The <code>handleCheck</code> function will return true if an items already exists in the array but I'm not sure how to then use this to prevent the item from being added to the array.</p>
<p>I have attempted to use it in the <code>handlePush</code> function <code>this.handleCheck(item) == false ?</code> it should check if it's false and if so then push, if it returns true it should say it exists but at the moment this is not working as it will push to the array even if the item exists and it will never console.log 'exists`</p>
<p>How can I change my handlePush function to use handleCheck and prevent an item that already exists in the array to be added again?</p>
<p><a href="https://www.webpackbin.com/bins/-KpnhkEKCpjXU0XlNlVm" rel="noreferrer">https://www.webpackbin.com/bins/-KpnhkEKCpjXU0XlNlVm</a></p>
<pre><code>import React from 'react'
import styled from 'styled-components'
import update from 'immutability-helper'
const Wrap = styled.div`
height: auto;
background: papayawhip;
width: 200px;
margin-bottom:10px;
`
export default class Hello extends React.Component {
constructor() {
super()
this.state = {
data: []
}
this.handlePush = this.handlePush.bind(this)
this.handleRemove = this.handleRemove.bind(this)
this.handleCheck = this.handleCheck.bind(this)
}
handlePush(item) {
this.handleCheck(item) == false ?
this.setState({
data: update(this.state.data, {
$push: [
item
]
})
})
: 'console.log('exists')
}
handleRemove(index) {
this.setState({
data: update(this.state.data, {
$splice: [
[index,1]
]
})
})
}
handleCheck(val) {
return this.state.data.some(item => val === item.name);
}
render() {
return(
<div>
<button onClick={() => this.handlePush({name: 'item2'})}>push</button>
<button onClick={() => this.handlePush({name: 'item3'})}>push item3</button>
{this.state.data.length > 1 ? this.state.data.map(product =>
<Wrap onClick={this.handleRemove}>{product.name}</Wrap>) : 'unable to map' }
{console.log(this.state.data)}
{console.log(this.handleCheck('item2'))}
{console.log(this.handleCheck('item3'))}
</div>
)
}
}
</code></pre> | 45,277,428 | 3 | 3 | null | 2017-07-24 09:46:55.54 UTC | 5 | 2020-06-10 05:08:56.783 UTC | null | null | null | null | 3,992,768 | null | 1 | 20 | javascript|arrays|reactjs | 122,437 | <p>it should be:</p>
<pre><code>handleCheck(val) {
return this.state.data.some(item => val.name === item.name);
}
</code></pre>
<p>because <code>val</code> here is an Object not a String.</p>
<p>Check this out:
<a href="https://www.webpackbin.com/bins/-Kpo0Rk6Z8ysenWttr7q" rel="noreferrer">https://www.webpackbin.com/bins/-Kpo0Rk6Z8ysenWttr7q</a></p> |
16,038,360 | Initialize database without XML configuration, but using @Configuration | <p>I would like to know how to initialize a database without having to create an XML file.</p>
<p>I already use this kind of initialization that works fine, but in my current case I don't want to create an XML:</p>
<pre><code><jdbc:initialize-database data-source="dataSource">
<jdbc:script location="classpath:com/foo/sql/db-schema.sql"/>
<jdbc:script location="classpath:com/foo/sql/db-test-data.sql"/>
</jdbc:initialize-database>
</code></pre>
<p>I know I can create an embedded database with:</p>
<pre><code>EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase db = builder.setType(H2).addScript("my-schema.sql").addScript("my-test-data.sql").build();
</code></pre>
<p>In my case, the database and schema are created using Liquibase.</p>
<p>I just want to initialize it with Spring and with my customized dataset, without having to create a new XML file each time just for that.</p>
<p>Is it possible?</p> | 16,039,725 | 4 | 0 | null | 2013-04-16 13:26:17.913 UTC | 20 | 2016-07-11 11:46:48.68 UTC | 2016-07-11 11:46:48.68 UTC | null | 309,683 | null | 82,609 | null | 1 | 43 | java|spring|h2 | 34,174 | <p>After looking at Spring classes related to EmbeddedDatabaseBuilder I found out that the DatabaseBuilder is using some code looking like this:</p>
<pre><code>ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
for (String sqlScript: sqlInitializationScripts ) {
Resource sqlScriptResource = RESOURCE_LOADER.getResource(sqlScript);
populator.addScript(sqlScriptResource);
}
DatabasePopulatorUtils.execute(populator, dataSource);
</code></pre>
<p>This will work fine for me, even if it will be on a @BeforeTest method and not on the Spring configuration.</p> |
51,091,539 | maven-site plugins 3.3 java.lang.ClassNotFoundException: org.apache.maven.doxia.siterenderer.DocumentContent | <p>Since this night, maven site 3.3 plugins stop to work.</p>
<p>Try to delete local repository, but no change.
Maven 3.3.9
java 1.8</p>
<p>No config or dependencies defined in pom for site plugins</p>
<pre><code>[WARNING] Error injecting: org.apache.maven.report.projectinfo.CiManagementReport
java.lang.NoClassDefFoundError: org/apache/maven/doxia/siterenderer/DocumentContent
</code></pre> | 51,093,732 | 8 | 1 | null | 2018-06-28 21:35:22.44 UTC | 23 | 2021-05-11 09:17:24.193 UTC | null | null | null | null | 10,007,946 | null | 1 | 118 | java|maven | 82,352 | <p>I had just started to get this issue also during builds. What worked for me was to specifically define the <code>maven-site-plugin</code> and the <code>maven-project-info-reports-plugin</code> along with the version numbers in the pom.</p>
<pre><code><plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</code></pre> |
10,435,591 | HG: find where a deleted line was removed | <p>I am looking for the mercurial equivalent of the solution to this question:</p>
<p><a href="https://stackoverflow.com/questions/4404444/how-do-i-blame-a-deleted-line">How do I "git blame" a deleted line?</a></p>
<p>In short, I am looking at a mercurial commit where a line was added, and in the current revision this line is no longer present, and I want to find when and why it was removed.</p> | 10,485,846 | 2 | 3 | null | 2012-05-03 16:33:24.473 UTC | 2 | 2020-01-03 13:52:46.78 UTC | 2017-05-23 12:33:02.277 UTC | null | -1 | null | 610,585 | null | 1 | 29 | mercurial|blame | 4,066 | <p><code>hg grep</code> will let you search a change log for a pattern, such as a deleted string. If you are looking for more than just the first occurrence, be sure to include the <code>--all</code> flag. For me it looked something like this:</p>
<p><code>hg grep --all -r 9876:tip "pattern" path/to/file</code></p>
<p>Thanks to Anton for the helpful comments and krtek for his <a href="https://stackoverflow.com/questions/9725856/">related answer</a>.</p> |
10,261,986 | How to detect string which contains only spaces? | <p>A string length which contains one space is always equal to 1:</p>
<pre><code>alert('My str length: ' + str.length);
</code></pre>
<p>The space is a character, so:</p>
<pre><code>str = " ";
alert('My str length:' + str.length); // My str length: 3
</code></pre>
<p>How can I make a distinction between an empty string and a string which contains only spaces? How can I detect a string which contain only spaces?</p> | 10,262,019 | 9 | 3 | null | 2012-04-21 18:56:33.467 UTC | 30 | 2022-08-05 06:15:40.84 UTC | 2018-09-24 18:12:44.517 UTC | null | 5,483,074 | null | 734,308 | null | 1 | 121 | javascript | 156,554 | <p>To achieve this you can use a Regular Expression to remove all the whitespace in the string. If the length of the resulting string is <code>0</code>, then you can be sure the original only contained whitespace. Try this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var str = " ";
if (!str.replace(/\s/g, '').length) {
console.log('string only contains whitespace (ie. spaces, tabs or line breaks)');
}</code></pre>
</div>
</div>
</p> |
10,386,672 | Reading whole files in Lua | <p>I am trying to read a full mp3 file in order to read out the id3 tags. That's when I noticed that file:read("*a") apparently does not read the full file but rather a small part. So I tried to build some kind of workaround in order to get the content of the whole file:</p>
<pre><code>function readAll(file)
local f = io.open(file, "r")
local content = ""
local length = 0
while f:read(0) ~= "" do
local current = f:read("*all")
print(#current, length)
length = length + #current
content = content .. current
end
return content
end
</code></pre>
<p>for my testfile, this shows that 256 reading operations are performed, reading a total of ~113kB (the whole file is ~7MB). Though this should be enough to read most id3 tags, I wonder why Lua behaves in this way (especially because it does not when reading large textbased files such as *.obj or *.ase). Is there any explanation for this behaviour or maybe a solution to reliably read the whole file?</p> | 10,387,949 | 1 | 4 | null | 2012-04-30 15:56:47.34 UTC | 6 | 2020-04-24 13:34:58.2 UTC | 2020-04-24 13:34:58.2 UTC | null | 570,336 | null | 570,336 | null | 1 | 24 | io|lua | 44,538 | <p>I must be missing something but I fail to see why a loop is needed. This should work (but you'd better add error handling in case the file cannot be opened):</p>
<pre><code>function readAll(file)
local f = assert(io.open(file, "rb"))
local content = f:read("*all")
f:close()
return content
end
</code></pre> |
50,549,128 | Boundary enclosing a given set of points | <p>I am having a bit of a problem with an algorithm that I am currently using. I wanted it to make a boundary. </p>
<p>Here is an example of the current behavior: </p>
<p><a href="https://i.imgur.com/wrhH4wh.png" rel="noreferrer"><img src="https://i.imgur.com/wrhH4wh.png" alt="Current behavior"></a></p>
<p>Here is an MSPaint example of wanted behavior:</p>
<p><a href="https://i.stack.imgur.com/1DSmi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1DSmi.png" alt="Wanted behavior"></a></p>
<p>Current code of Convex Hull in C#:<a href="https://hastebin.com/dudejesuja.cs" rel="noreferrer">https://hastebin.com/dudejesuja.cs</a></p>
<p>So here are my questions:</p>
<p>1) Is this even possible?</p>
<p>R: Yes</p>
<p>2) Is this even called Convex Hull? (I don't think so)</p>
<p>R: Nope it is called boundary, link: <a href="https://www.mathworks.com/help/matlab/ref/boundary.html" rel="noreferrer">https://www.mathworks.com/help/matlab/ref/boundary.html</a></p>
<p>3) Will this be less performance friendly than a conventional convex hull?</p>
<p>R: Well as far as I researched it should be the same performance</p>
<p>4) Example of this algorithm in pseudo code or something similar?</p>
<p>R: Not answered yet or I didn't find a solution yet</p> | 50,714,300 | 6 | 13 | null | 2018-05-27 04:56:32.36 UTC | 10 | 2022-08-18 07:59:32.18 UTC | 2018-05-29 12:37:39.477 UTC | null | 1,332,041 | null | 8,093,775 | null | 1 | 13 | geometry|computational-geometry|concave-hull | 13,050 | <p>Here is some Python code that computes the alpha-shape (concave hull) and keeps only the outer boundary. This is probably what matlab's boundary does inside.</p>
<pre><code>from scipy.spatial import Delaunay
import numpy as np
def alpha_shape(points, alpha, only_outer=True):
"""
Compute the alpha shape (concave hull) of a set of points.
:param points: np.array of shape (n,2) points.
:param alpha: alpha value.
:param only_outer: boolean value to specify if we keep only the outer border
or also inner edges.
:return: set of (i,j) pairs representing edges of the alpha-shape. (i,j) are
the indices in the points array.
"""
assert points.shape[0] > 3, "Need at least four points"
def add_edge(edges, i, j):
"""
Add an edge between the i-th and j-th points,
if not in the list already
"""
if (i, j) in edges or (j, i) in edges:
# already added
assert (j, i) in edges, "Can't go twice over same directed edge right?"
if only_outer:
# if both neighboring triangles are in shape, it's not a boundary edge
edges.remove((j, i))
return
edges.add((i, j))
tri = Delaunay(points)
edges = set()
# Loop over triangles:
# ia, ib, ic = indices of corner points of the triangle
for ia, ib, ic in tri.vertices:
pa = points[ia]
pb = points[ib]
pc = points[ic]
# Computing radius of triangle circumcircle
# www.mathalino.com/reviewer/derivation-of-formulas/derivation-of-formula-for-radius-of-circumcircle
a = np.sqrt((pa[0] - pb[0]) ** 2 + (pa[1] - pb[1]) ** 2)
b = np.sqrt((pb[0] - pc[0]) ** 2 + (pb[1] - pc[1]) ** 2)
c = np.sqrt((pc[0] - pa[0]) ** 2 + (pc[1] - pa[1]) ** 2)
s = (a + b + c) / 2.0
area = np.sqrt(s * (s - a) * (s - b) * (s - c))
circum_r = a * b * c / (4.0 * area)
if circum_r < alpha:
add_edge(edges, ia, ib)
add_edge(edges, ib, ic)
add_edge(edges, ic, ia)
return edges
</code></pre>
<p>If you run it with the following test code you will get this figure, which looks like what you need:
<a href="https://i.stack.imgur.com/C8sRU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/C8sRU.png" alt="enter image description here"></a></p>
<pre><code>from matplotlib.pyplot import *
# Constructing the input point data
np.random.seed(0)
x = 3.0 * np.random.rand(2000)
y = 2.0 * np.random.rand(2000) - 1.0
inside = ((x ** 2 + y ** 2 > 1.0) & ((x - 3) ** 2 + y ** 2 > 1.0)
points = np.vstack([x[inside], y[inside]]).T
# Computing the alpha shape
edges = alpha_shape(points, alpha=0.25, only_outer=True)
# Plotting the output
figure()
axis('equal')
plot(points[:, 0], points[:, 1], '.')
for i, j in edges:
plot(points[[i, j], 0], points[[i, j], 1])
show()
</code></pre>
<p>EDIT: Following a request in a comment, here is some code that "stitches" the output edge set into sequences of consecutive edges.</p>
<pre><code>def find_edges_with(i, edge_set):
i_first = [j for (x,j) in edge_set if x==i]
i_second = [j for (j,x) in edge_set if x==i]
return i_first,i_second
def stitch_boundaries(edges):
edge_set = edges.copy()
boundary_lst = []
while len(edge_set) > 0:
boundary = []
edge0 = edge_set.pop()
boundary.append(edge0)
last_edge = edge0
while len(edge_set) > 0:
i,j = last_edge
j_first, j_second = find_edges_with(j, edge_set)
if j_first:
edge_set.remove((j, j_first[0]))
edge_with_j = (j, j_first[0])
boundary.append(edge_with_j)
last_edge = edge_with_j
elif j_second:
edge_set.remove((j_second[0], j))
edge_with_j = (j, j_second[0]) # flip edge rep
boundary.append(edge_with_j)
last_edge = edge_with_j
if edge0[0] == last_edge[1]:
break
boundary_lst.append(boundary)
return boundary_lst
</code></pre>
<p>You can then go over the list of boundary lists and append the points corresponding to the first index in each edge to get a boundary polygon.</p> |
35,739,743 | File res/drawable/abc_ic_ab_back_material.xml from drawable resource ID #0x7f020016 | <p>Recently <code>android support library</code> was updated to <code>23.2.0</code>. After downloading android sdk and updating android design support library into <code>23.2.0</code>, this error happens repeatedly. My project can't even be compiled. The complete error log says:</p>
<pre><code>03-02 12:00:04.945 9324-9324/com.creditease.zhiwang.debug E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.creditease.zhiwang.debug/com.creditease.zhiwang.activity.TabContainerActivity}: android.content.res.Resources$NotFoundException: File res/drawable/abc_ic_ab_back_material.xml from drawable resource ID #0x7f020016
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2309)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
at android.app.ActivityThread.access$700(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5528)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/abc_ic_ab_back_material.xml from drawable resource ID #0x7f020016
at android.content.res.Resources.loadDrawable(Resources.java:2974)
at android.content.res.Resources.getDrawable(Resources.java:1558)
at android.support.v7.widget.TintResources.superGetDrawable(TintResources.java:48)
at android.support.v7.widget.AppCompatDrawableManager.onDrawableLoadedFromResources(AppCompatDrawableManager.java:374)
at android.support.v7.widget.TintResources.getDrawable(TintResources.java:44)
at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:323)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:180)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:173)
at android.support.v7.widget.ToolbarWidgetWrapper.<init>(ToolbarWidgetWrapper.java:184)
at android.support.v7.widget.ToolbarWidgetWrapper.<init>(ToolbarWidgetWrapper.java:91)
at android.support.v7.app.ToolbarActionBar.<init>(ToolbarActionBar.java:74)
at android.support.v7.app.AppCompatDelegateImplV7.setSupportActionBar(AppCompatDelegateImplV7.java:210)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:119)
at com.creditease.zhiwang.activity.BaseActivity.initToolBar(BaseActivity.java:300)
at com.creditease.zhiwang.activity.BaseActivity.initToolBar(BaseActivity.java:265)
at com.creditease.zhiwang.activity.TabContainerActivity.onCreate(TabContainerActivity.java:107)
at android.app.Activity.performCreate(Activity.java:5372)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2271)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
at android.app.ActivityThread.access$700(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5528)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
at dalvik.system.NativeStart.main(Native Method)
Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #17: invalid drawable tag vector
at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:933)
at android.graphics.drawable.Drawable.createFromXml(Drawable.java:873)
at android.content.res.Resources.loadDrawable(Resources.java:2970)
at android.content.res.Resources.getDrawable(Resources.java:1558)
at android.support.v7.widget.TintResources.superGetDrawable(TintResources.java:48)
at android.support.v7.widget.AppCompatDrawableManager.onDrawableLoadedFromResources(AppCompatDrawableManager.java:374)
at android.support.v7.widget.TintResources.getDrawable(TintResources.java:44)
at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:323)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:180)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:173)
at android.support.v7.widget.ToolbarWidgetWrapper.<init>(ToolbarWidgetWrapper.java:184)
at android.support.v7.widget.ToolbarWidgetWrapper.<init>(ToolbarWidgetWrapper.java:91)
at android.support.v7.app.ToolbarActionBar.<init>(ToolbarActionBar.java:74)
at android.support.v7.app.AppCompatDelegateImplV7.setSupportActionBar(AppCompatDelegateImplV7.java:210)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:119)
at com.creditease.zhiwang.activity.BaseActivity.initToolBar(BaseActivity.java:300)
at com.creditease.zhiwang.activity.BaseActivity.initToolBar(BaseActivity.java:265)
at com.creditease.zhiwang.activity.TabContainerActivity.onCreate(TabContainerActivity.java:107)
at android.app.Activity.performCreate(Activity.java:5372)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2271)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
at android.app.ActivityThread.access$700(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5528)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>This error was thrown by <code>setSupportActionBar(toolbar);</code> whereas it didn't happen at <code>23.0.1</code> of <code>android design library 23.2.0</code>. Meanwhile according this log, I guessed this drawable was removed since <code>android design library 23.2.0</code>.</p>
<p>So, could someone told me why is this happening?</p> | 35,740,506 | 7 | 8 | null | 2016-03-02 06:08:52.167 UTC | 8 | 2021-08-13 10:31:23.323 UTC | 2016-03-02 06:25:04.093 UTC | null | 3,260,248 | null | 4,407,176 | null | 1 | 25 | android|android-gradle-plugin|android-design-library | 32,968 | <p>I think you need to make changes in your <code>gradle</code>.</p>
<pre><code>// Gradle Plugin 2.0+
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
</code></pre>
<p>You’ll note this new attribute only exists in the version 2.0 of the Gradle Plugin. If you are using Gradle 1.5 you’ll instead use</p>
<pre><code>// Gradle Plugin 1.5
android {
defaultConfig {
// Stops the Gradle plugin's automatic rasterization of vectors
generatedDensities = []
}
// Flag to tell aapt to keep the attribute ids around
// This is handled for you by the 2.0+ Gradle Plugin
aaptOptions {
additionalParameters "--no-version-vectors"
}
}
</code></pre>
<p>I found similar question <a href="https://stackoverflow.com/questions/35622438/update-android-support-library-to-23-2-0-cause-error-xmlpullparserexception-bin">here</a>.</p>
<p>See <a href="http://android-developers.blogspot.in/2016/02/android-support-library-232.html" rel="nofollow noreferrer">Support Vector Drawables and Animated Vector Drawables</a> in Android Support Library update.
I hope its help you.</p> |
33,335,838 | Why does this multi-threaded code print 6 some of the time? | <p>I'm creating two threads, and passing them a function which executes the code show below, 10,000,000 times.</p>
<p>Mostly, "5" is printed to the console. Sometimes it's "3" or "4". It's pretty clear why this is happening.</p>
<p>However, it's also printing "6". How is this possible?</p>
<pre><code>class Program
{
private static int _state = 3;
static void Main(string[] args)
{
Thread firstThread = new Thread(Tr);
Thread secondThread = new Thread(Tr);
firstThread.Start();
secondThread.Start();
firstThread.Join();
secondThread.Join();
Console.ReadLine();
}
private static void Tr()
{
for (int i = 0; i < 10000000; i++)
{
if (_state == 3)
{
_state++;
if (_state != 4)
{
Console.Write(_state);
}
_state = 3;
}
}
}
}
</code></pre>
<p>Here is the output:</p>
<p><a href="https://i.stack.imgur.com/wvAVz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wvAVz.png" alt="Enter image description here"></a></p> | 33,335,962 | 2 | 8 | null | 2015-10-25 22:30:06.42 UTC | 9 | 2020-06-25 08:47:49.303 UTC | 2018-02-22 02:11:18.303 UTC | null | 563,532 | null | 4,756,394 | null | 1 | 31 | c#|multithreading | 2,592 | <p>I <em>think</em> I have figured out the sequence of events leading to this issue:</p>
<p>Thread 1 enters <code>if (_state == 3)</code> </p>
<p><strong><em>Context switch</em></strong></p>
<p>Thread 2 enters <code>if (_state == 3)</code><br>
Thread 2 increments state (<code>state = 4</code>) </p>
<p><strong><em>Context switch</em></strong></p>
<p>Thread 1 <em>reads</em> <code>_state</code> as <code>4</code> </p>
<p><strong><em>Context switch</em></strong></p>
<p>Thread 2 sets <code>_state = 3</code><br>
Thread 2 enters <code>if (_state == 3)</code> </p>
<p><strong><em>Context switch</em></strong></p>
<p>Thread 1 executes <code>_state = 4 + 1</code> </p>
<p><strong><em>Context switch</em></strong></p>
<p>Thread 2 reads <code>_state</code> as <code>5</code><br>
Thread 2 executes <code>_state = 5 + 1</code>; </p> |
13,733,506 | Facebook One or more of the given URLs is not allowed by the App's settings | <p>Result in console:</p>
<blockquote>
<p>Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains. </p>
</blockquote>
<p>Basically what I am trying is to enable user to login on my blog on blogspot.com, and to post on his wall some message.</p>
<p>here is how I configure app on facebook:<br />
<strong>App Domains</strong>:blogspot.com <br />
<strong>Sandbox Mode</strong>:disabled <br />
<strong>Site URL</strong>:my_blog_name.blogspot.com/p/publishing.html</p> | 13,768,522 | 12 | 0 | null | 2012-12-05 22:18:22.287 UTC | 6 | 2020-03-15 11:09:12.623 UTC | 2012-12-07 17:53:37.18 UTC | null | 637,307 | null | 637,307 | null | 1 | 13 | facebook|facebook-apps|facebook-authentication|blogspot | 97,963 | <p>after putting <strong>site url</strong> to begin with <strong>http://</strong> it resolve my issue.
Now my <strong>Site URL</strong> looks like this: <a href="http://my_blog_name.blogspot.com/p/publishing.html" rel="noreferrer">http://my_blog_name.blogspot.com/p/publishing.html</a></p> |
13,660,761 | How to convert Turkish chars to English chars in a string? | <p>string strTurkish = "ÜST"; </p>
<p>how to make value of strTurkish as "UST" ?</p> | 13,660,822 | 7 | 2 | null | 2012-12-01 15:17:07.577 UTC | 8 | 2022-01-26 13:50:07.217 UTC | null | null | null | null | 712,847 | null | 1 | 20 | c#|encoding | 22,755 | <pre><code>var text = "ÜST";
var unaccentedText = String.Join("", text.Normalize(NormalizationForm.FormD)
.Where(c => char.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark));
</code></pre> |
13,709,830 | Override file while backup database | <p>I want to back up a database using this code</p>
<pre><code>sqlcmd -S servername -Q "BACKUP DATABASE [DBName] TO DISK = 'C:\backup.bak'"
</code></pre>
<p>It works. But if the backup file already exists, the data gets appended to the file instead of replacing the file. Every time I call <code>BACKUP DATABASE</code> the file gets bigger.</p>
<p>Is there an option for <code>BACKUP DATABASE</code> to force a replace?</p> | 13,709,933 | 4 | 0 | null | 2012-12-04 18:48:41.43 UTC | 6 | 2021-12-18 22:29:09.403 UTC | null | null | null | null | 575,376 | null | 1 | 47 | sql-server|database|backup|database-backups | 52,894 | <pre><code>sqlcmd -S servername -Q "BACKUP DATABASE [DBName] TO DISK = 'C:\backup.bak' WITH INIT"
</code></pre> |
13,385,860 | How can I remove extra whitespace from strings when parsing a csv file in Pandas? | <p>I have the following file named 'data.csv':</p>
<pre><code> 1997,Ford,E350
1997, Ford , E350
1997,Ford,E350,"Super, luxurious truck"
1997,Ford,E350,"Super ""luxurious"" truck"
1997,Ford,E350," Super luxurious truck "
"1997",Ford,E350
1997,Ford,E350
2000,Mercury,Cougar
</code></pre>
<p>And I would like to parse it into a pandas DataFrame so that the DataFrame looks as follows:</p>
<pre><code> Year Make Model Description
0 1997 Ford E350 None
1 1997 Ford E350 None
2 1997 Ford E350 Super, luxurious truck
3 1997 Ford E350 Super "luxurious" truck
4 1997 Ford E350 Super luxurious truck
5 1997 Ford E350 None
6 1997 Ford E350 None
7 2000 Mercury Cougar None
</code></pre>
<p>The best I could do was:</p>
<pre><code> pd.read_table("data.csv", sep=r',', names=["Year", "Make", "Model", "Description"])
</code></pre>
<p>Which gets me:</p>
<pre><code> Year Make Model Description
0 1997 Ford E350 None
1 1997 Ford E350 None
2 1997 Ford E350 Super, luxurious truck
3 1997 Ford E350 Super "luxurious" truck
4 1997 Ford E350 Super luxurious truck
5 1997 Ford E350 None
6 1997 Ford E350 None
7 2000 Mercury Cougar None
</code></pre>
<p>How can I get the DataFrame without those whitespaces?</p> | 13,386,025 | 9 | 0 | null | 2012-11-14 19:25:28.74 UTC | 29 | 2021-10-19 21:59:44.5 UTC | 2012-11-14 19:38:36.557 UTC | null | 982,257 | null | 1,715,271 | null | 1 | 66 | python|parsing|pandas | 81,551 | <p>You could use converters:</p>
<pre><code>import pandas as pd
def strip(text):
try:
return text.strip()
except AttributeError:
return text
def make_int(text):
return int(text.strip('" '))
table = pd.read_table("data.csv", sep=r',',
names=["Year", "Make", "Model", "Description"],
converters = {'Description' : strip,
'Model' : strip,
'Make' : strip,
'Year' : make_int})
print(table)
</code></pre>
<p>yields</p>
<pre><code> Year Make Model Description
0 1997 Ford E350 None
1 1997 Ford E350 None
2 1997 Ford E350 Super, luxurious truck
3 1997 Ford E350 Super "luxurious" truck
4 1997 Ford E350 Super luxurious truck
5 1997 Ford E350 None
6 1997 Ford E350 None
7 2000 Mercury Cougar None
</code></pre> |
13,397,691 | How can I send a success status to browser from nodejs/express? | <p>I've written the following piece of code in my nodeJS/Expressjs server:</p>
<pre><code>app.post('/settings', function(req, res){
var myData = {
a: req.param('a')
,b: req.param('b')
,c: req.param('c')
,d: req.param('d')
}
var outputFilename = 'config.json';
fs.writeFile(outputFilename, JSON.stringify(myData, null, 4), function(err) {
if(err) {
console.log(err);
} else {
console.log("Config file as been overwriten");
}
});
});
</code></pre>
<p>This allows me to get the submitted form data and write it to a JSON file.</p>
<p>This works perfectly. But the client remains in some kind of posting state and eventually times out. So I need to send some kind of success state or success header back to the client. </p>
<p>How should I do this?</p>
<p>Thank you in advance!</p> | 28,593,775 | 4 | 0 | null | 2012-11-15 12:38:48.57 UTC | 8 | 2019-06-05 13:47:34.26 UTC | 2019-06-05 13:47:34.26 UTC | null | 3,702,088 | null | 1,077,230 | null | 1 | 83 | forms|node.js|post|express | 105,263 | <p><strong>Express Update 2015:</strong></p>
<p>Use this instead: </p>
<pre><code>res.sendStatus(200)
</code></pre>
<p>This has been deprecated:</p>
<pre><code>res.send(200)
</code></pre> |
13,437,362 | How to get the first and last date of the current year? | <p>Using SQL Server 2000, how can I get the first and last date of the current year?</p>
<p>Expected Output:</p>
<p><code>01/01/2012</code> and <code>31/12/2012</code></p> | 13,437,389 | 19 | 0 | null | 2012-11-18 04:02:08.003 UTC | 30 | 2021-03-16 12:09:22.01 UTC | 2018-01-02 16:45:24.64 UTC | null | 2,756,409 | null | 128,071 | null | 1 | 135 | sql|sql-server|sql-server-2000 | 450,614 | <pre><code>SELECT
DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AS StartOfYear,
DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1) AS EndOfYear
</code></pre>
<p>The above query gives a datetime value for midnight at the beginning of December 31. This is about 24 hours short of the last moment of the year. If you want to include time that might occur on December 31, then you should compare to the first of the next year, with a <code><</code> comparison. Or you can compare to the last few milliseconds of the current year, but this still leaves a gap if you are using something other than DATETIME (such as DATETIME2):</p>
<pre><code>SELECT
DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AS StartOfYear,
DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1) AS LastDayOfYear,
DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, 0) AS FirstOfNextYear,
DATEADD(ms, -3, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, 0)) AS LastTimeOfYear
</code></pre>
<p><strong>Other Periods</strong></p>
<p>This approach has two nice aspects: good performance and it can easily be changed for other periods by replacing both occurrences of <code>yy</code> (=year) with a different string:</p>
<pre><code>yy, yyyy year
qq, q quarter
mm, m month
wk, ww week
</code></pre>
<p>(Be careful of weeks: the starting day depends on server settings.)</p>
<p><strong>Tech Details</strong></p>
<p>This works by figuring out the number of years since 1900 with <code>DATEDIFF(yy, 0, GETDATE())</code> and then adding that to a date of zero = Jan 1, 1900. This can be changed to work for an arbitrary date by replacing the <code>GETDATE()</code> portion or an arbitrary year by replacing the <code>DATEDIFF(...)</code> function with "Year - 1900."</p>
<pre><code> SELECT
DATEADD(yy, DATEDIFF(yy, 0, '20150301'), 0) AS StartOfYearForMarch2015,
DATEADD(yy, 2015 - 1900, 0) AS StartOfYearFor2015
</code></pre> |
51,710,037 | How should I use the Optional type hint? | <p>I'm trying to understand how to use the <code>Optional</code> type hint. From <a href="https://www.python.org/dev/peps/pep-0484/" rel="noreferrer">PEP-484</a>, I know I can use <code>Optional</code> for <code>def test(a: int = None)</code> either as <code>def test(a: Union[int, None])</code> or <code>def test(a: Optional[int])</code>. </p>
<p>But how about following examples?</p>
<pre><code>def test(a : dict = None):
#print(a) ==> {'a': 1234}
#or
#print(a) ==> None
def test(a : list = None):
#print(a) ==> [1,2,3,4, 'a', 'b']
#or
#print(a) ==> None
</code></pre>
<p>If <code>Optional[type]</code> seems to mean the same thing as <code>Union[type, None]</code>, why should I use <code>Optional[]</code> at all?</p> | 51,710,151 | 5 | 3 | null | 2018-08-06 14:33:53.053 UTC | 63 | 2022-07-30 01:38:56.903 UTC | 2021-10-06 13:54:38.293 UTC | null | 13,990,016 | null | 6,373,357 | null | 1 | 270 | python|python-3.x|type-hinting|python-typing | 232,146 | <p><code>Optional[...]</code> is a shorthand notation for <code>Union[..., None]</code>, telling the type checker that either an object of the specific type is required, <em>or</em> <code>None</code> is required. <code>...</code> stands for <em>any valid type hint</em>, including complex compound types or a <code>Union[]</code> of more types. Whenever you have a keyword argument with default value <code>None</code>, you should use <code>Optional</code>. (Note: If you are targeting Python 3.10 or newer, <a href="https://www.python.org/dev/peps/pep-0604/" rel="noreferrer">PEP 604</a> introduced a better syntax, see below).</p>
<p>So for your two examples, you have <code>dict</code> and <code>list</code> container types, but the default value for the <code>a</code> keyword argument shows that <code>None</code> is permitted too so use <code>Optional[...]</code>:</p>
<pre><code>from typing import Optional
def test(a: Optional[dict] = None) -> None:
#print(a) ==> {'a': 1234}
#or
#print(a) ==> None
def test(a: Optional[list] = None) -> None:
#print(a) ==> [1, 2, 3, 4, 'a', 'b']
#or
#print(a) ==> None
</code></pre>
<p>There is technically no difference between using <code>Optional[]</code> on a <code>Union[]</code>, or just adding <code>None</code> to the <code>Union[]</code>. So <code>Optional[Union[str, int]]</code> and <code>Union[str, int, None]</code> are exactly the same thing.</p>
<p>Personally, I'd stick with <em>always</em> using <code>Optional[]</code> when setting the type for a keyword argument that uses <code>= None</code> to set a default value, this documents the reason why <code>None</code> is allowed better. Moreover, it makes it easier to move the <code>Union[...]</code> part into a separate type alias, or to later remove the <code>Optional[...]</code> part if an argument becomes mandatory.</p>
<p>For example, say you have</p>
<pre><code>from typing import Optional, Union
def api_function(optional_argument: Optional[Union[str, int]] = None) -> None:
"""Frob the fooznar.
If optional_argument is given, it must be an id of the fooznar subwidget
to filter on. The id should be a string, or for backwards compatibility,
an integer is also accepted.
"""
</code></pre>
<p>then documentation is improved by pulling out the <code>Union[str, int]</code> into a type alias:</p>
<pre><code>from typing import Optional, Union
# subwidget ids used to be integers, now they are strings. Support both.
SubWidgetId = Union[str, int]
def api_function(optional_argument: Optional[SubWidgetId] = None) -> None:
"""Frob the fooznar.
If optional_argument is given, it must be an id of the fooznar subwidget
to filter on. The id should be a string, or for backwards compatibility,
an integer is also accepted.
"""
</code></pre>
<p>The refactor to move the <code>Union[]</code> into an alias was made all the much easier because <code>Optional[...]</code> was used instead of <code>Union[str, int, None]</code>. The <code>None</code> value is not a 'subwidget id' after all, it's not part of the value, <code>None</code> is meant to flag the absence of a value.</p>
<p>Side note: Unless your code only has to support Python 3.9 or newer, you want to avoid using the standard library container types in type hinting, as you can't say anything about what types they must contain. So instead of <code>dict</code> and <code>list</code>, use <code>typing.Dict</code> and <code>typing.List</code>, respectively. And when only <em>reading</em> from a container type, you may just as well accept any immutable abstract container type; lists and tuples are <code>Sequence</code> objects, while <code>dict</code> is a <code>Mapping</code> type:</p>
<pre><code>from typing import Mapping, Optional, Sequence, Union
def test(a: Optional[Mapping[str, int]] = None) -> None:
"""accepts an optional map with string keys and integer values"""
# print(a) ==> {'a': 1234}
# or
# print(a) ==> None
def test(a: Optional[Sequence[Union[int, str]]] = None) -> None:
"""accepts an optional sequence of integers and strings
# print(a) ==> [1, 2, 3, 4, 'a', 'b']
# or
# print(a) ==> None
</code></pre>
<p>In Python 3.9 and up, the standard container types have all been updated to support using them in type hints, see <a href="https://www.python.org/dev/peps/pep-0585/" rel="noreferrer">PEP 585</a>. <em>But</em>, while you now <em>can</em> use <code>dict[str, int]</code> or <code>list[Union[int, str]]</code>, you still may want to use the more expressive <code>Mapping</code> and <code>Sequence</code> annotations to indicate that a function won't be mutating the contents (they are treated as 'read only'), and that the functions would work with <em>any</em> object that works as a mapping or sequence, respectively.</p>
<p>Python 3.10 introduces the <code>|</code> union operator into type hinting, see <a href="https://www.python.org/dev/peps/pep-0604/" rel="noreferrer">PEP 604</a>. Instead of <code>Union[str, int]</code> you can write <code>str | int</code>. In line with other type-hinted languages, the preferred (and more concise) way to denote an optional argument in Python 3.10 and up, is now <code>Type | None</code>, e.g. <code>str | None</code> or <code>list | None</code>.</p> |
24,027,116 | How can I extend typed Arrays in Swift? | <p>How can I extend Swift's <code>Array<T></code> or <code>T[]</code> type with custom functional utils? </p>
<p>Browsing around Swift's API docs shows that Array methods are an extension of the <code>T[]</code>, e.g:</p>
<pre><code>extension T[] : ArrayType {
//...
init()
var count: Int { get }
var capacity: Int { get }
var isEmpty: Bool { get }
func copy() -> T[]
}
</code></pre>
<p>When copying and pasting the same source and trying any variations like:</p>
<pre><code>extension T[] : ArrayType {
func foo(){}
}
extension T[] {
func foo(){}
}
</code></pre>
<p>It fails to build with the error:</p>
<blockquote>
<p>Nominal type <code>T[]</code> can't be extended</p>
</blockquote>
<p>Using the full type definition fails with <code>Use of undefined type 'T'</code>, i.e:</p>
<pre><code>extension Array<T> {
func foo(){}
}
</code></pre>
<p>And it also fails with <code>Array<T : Any></code> and <code>Array<String></code>.</p>
<p>Curiously Swift lets me extend an untyped array with:</p>
<pre><code>extension Array {
func each(fn: (Any) -> ()) {
for i in self {
fn(i)
}
}
}
</code></pre>
<p>Which it lets me call with:</p>
<pre><code>[1,2,3].each(println)
</code></pre>
<p>But I can't create a proper generic type extension as the type seems to be lost when it flows through the method, e.g trying to <a href="https://stackoverflow.com/q/24025633/85785">replace Swift's built-in filter with</a>:</p>
<pre><code>extension Array {
func find<T>(fn: (T) -> Bool) -> T[] {
var to = T[]()
for x in self {
let t = x as T
if fn(t) {
to += t
}
}
return to
}
}
</code></pre>
<p>But the compiler treats it as untyped where it still allows calling the extension with: </p>
<pre><code>["A","B","C"].find { $0 > "A" }
</code></pre>
<p>And when stepped-thru with a debugger indicates the type is <code>Swift.String</code> but it's a build error to try access it like a String without casting it to <code>String</code> first, i.e:</p>
<pre><code>["A","B","C"].find { ($0 as String).compare("A") > 0 }
</code></pre>
<p>Does anyone know what's the proper way to create a typed extension method that acts like the built-in extensions?</p> | 33,557,647 | 11 | 2 | null | 2014-06-04 00:26:14.103 UTC | 63 | 2022-09-13 21:11:11.293 UTC | 2017-05-23 12:10:26.62 UTC | null | -1 | null | 85,785 | null | 1 | 243 | arrays|swift | 106,842 | <p>For extending typed arrays with <strong>classes</strong>, the below works for me (Swift <strong>2.2</strong>). For example, sorting a typed array:</p>
<pre><code>class HighScoreEntry {
let score:Int
}
extension Array where Element == HighScoreEntry {
func sort() -> [HighScoreEntry] {
return sort { $0.score < $1.score }
}
}
</code></pre>
<p>Trying to do this with a <strong>struct</strong> or <strong>typealias</strong> will give an error:</p>
<pre><code>Type 'Element' constrained to a non-protocol type 'HighScoreEntry'
</code></pre>
<p><strong>Update</strong>: </p>
<p>To extend typed arrays with <strong>non-classes</strong> use the following approach:</p>
<pre><code>typealias HighScoreEntry = (Int)
extension SequenceType where Generator.Element == HighScoreEntry {
func sort() -> [HighScoreEntry] {
return sort { $0 < $1 }
}
}
</code></pre>
<p>In <strong>Swift 3</strong> some types have been renamed:</p>
<pre><code>extension Sequence where Iterator.Element == HighScoreEntry
{
// ...
}
</code></pre> |
24,040,165 | jQuery Datepicker close datepicker after selected date | <p>HTML:</p>
<pre><code><div class="container">
<div class="hero-unit">
<input type="text" placeholder="click to show datepicker" id="example1">
</div>
</div>
</code></pre>
<p>jQuery:</p>
<pre><code><script type="text/javascript">
$(document).ready(function () {
$('#example1').datepicker({
format: "dd/mm/yyyy"
});
});
</script>
</code></pre>
<p>I use bootstrap datepicker.</p>
<p>When I click to datepicker it opens and I select any date.</p>
<p><strong>My question:</strong></p>
<blockquote>
<p>If I choose date from datepicker, I want to close datepicker popup.</p>
</blockquote>
<p>Which event do i need to use in order to close datepicker on select date?</p>
<p><strong>Edited:</strong></p>
<p><strong>I have found a solution</strong></p>
<p>This works</p>
<pre><code> $(document).mouseup(function (e) {
$('#example1').Close();
});
</code></pre>
<p>But this <strong>below</strong> does not work why ?</p>
<pre><code> $('#example1').datepicker().on('changeDate', function (ev) {
$('#example1').Close();
});
</code></pre> | 24,041,047 | 5 | 3 | null | 2014-06-04 14:27:18.557 UTC | 12 | 2021-11-17 17:26:13.623 UTC | 2014-12-03 16:15:56.987 UTC | null | 814,702 | null | 3,705,822 | null | 1 | 42 | javascript|jquery|twitter-bootstrap|datepicker | 232,346 | <p>Actually you don't need to replace this all (@Ben Rhouma Zied answere)....</p>
<p>There are 2 ways to do this. One is to use autoclose property, the other (alternativ) way is to use the on change property thats fired by the input when selecting a Date.</p>
<p><strong>HTML</strong></p>
<pre><code><div class="container">
<div class="hero-unit">
<input type="text" placeholder="Sample 1: Click to show datepicker" id="example1">
</div>
<div class="hero-unit">
<input type="text" placeholder="Sample 2: Click to show datepicker" id="example2">
</div>
</div>
</code></pre>
<p><strong>jQuery</strong></p>
<pre><code>$(document).ready(function () {
$('#example1').datepicker({
format: "dd/mm/yyyy",
autoclose: true
});
//Alternativ way
$('#example2').datepicker({
format: "dd/mm/yyyy"
}).on('change', function(){
$('.datepicker').hide();
});
});
</code></pre>
<p>this is all you have to do :)</p>
<p><strong><a href="http://jsfiddle.net/ma3rR/403/" rel="nofollow noreferrer">HERE IS A FIDDLE</a></strong> to see whats happening.</p>
<p><strong>Fiddleupdate on 13 of July 2016: CDN wasnt present anymore</strong></p>
<p>According to your EDIT:</p>
<pre><code>$('#example1').datepicker().on('changeDate', function (ev) {
$('#example1').Close();
});
</code></pre>
<p>Here you take the Input (that has no Close-Function) and create a Datepicker-Element. If the element changes you want to close it but you still try to close the Input (That has no close-function).</p>
<blockquote>
<p>Binding a mouseup event to the document state <strong>may not</strong> be the best idea because you will fire all containing scripts on each click!</p>
</blockquote>
<p>Thats it :)</p>
<p><strong>EDIT: August 2017 (Added a StackOverFlowFiddle aka Snippet. Same as in Top of Post)</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function () {
$('#example1').datepicker({
format: "dd/mm/yyyy",
autoclose: true
});
//Alternativ way
$('#example2').datepicker({
format: "dd/mm/yyyy"
}).on('change', function(){
$('.datepicker').hide();
});
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hero-unit{
float: left;
width: 210px;
margin-right: 25px;
}
.hero-unit input{
width: 100%;
}</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://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="container">
<div class="hero-unit">
<input type="text" placeholder="Sample 1: Click to show datepicker" id="example1">
</div>
<div class="hero-unit">
<input type="text" placeholder="Sample 2: Click to show datepicker" id="example2">
</div>
</div></code></pre>
</div>
</div>
</p>
<p><strong>EDIT: December 2018 Obviously Bootstrap-Datepicker doesnt work with jQuery 3.x <a href="https://stackoverflow.com/questions/41236574/bootstrap-datetimepicker-not-working-with-the-jquery-3">see this to fix</a></strong></p> |
3,987,150 | Sorted dataview to datatable | <p>I have the following method:</p>
<pre><code>private DataTable getsortedtable(DataTable dt)
{
dt.DefaultView.Sort = "Name desc";
//I would need to return the datatable sorted.
}
</code></pre>
<p>My issue is that I cannot change the return type of this method and I have to return a DataTable but i would like return it sorted.</p>
<p>Are there any magic hidden property of <code>dt.DefaultView</code> to return the dt sorted?</p> | 3,987,217 | 2 | 0 | null | 2010-10-21 11:56:46.89 UTC | 3 | 2019-06-18 19:55:31.577 UTC | 2019-06-18 19:55:31.577 UTC | null | 2,756,409 | null | 79,919 | null | 1 | 14 | c#|asp.net|datatable|dataview | 39,032 | <pre><code> private DataTable getSortedTable(DataTable dt)
{
dt.DefaultView.Sort = "columnName DESC";
return dt.DefaultView.ToTable();
}
</code></pre> |
3,538,293 | Regular expression - PCRE does not support \L, \l, \N, \P, | <p>I need to use the following regular expression to validate some Asian characters</p>
<pre><code> $regexp = "/^[\-'\u2e80-\u9fff\sa-zA-Z.]+$/"; // with warning
$regexp = "/^[\-'\sa-zA-Z.]+$/"; // without warning
</code></pre>
<p>preg_match() [function.preg-match]: Compilation failed: PCRE does not support \L, \l, \N, \P, \p, \U, \u, or \X.</p>
<p>Do you know how to change the regular expression pattern so that I can validate the Asian characters from <code>\u2e80-\u9fff</code></p>
<p>I am using the latest XAMPP</p>
<pre><code>Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1
</code></pre> | 3,538,296 | 2 | 1 | null | 2010-08-21 17:11:47.257 UTC | 11 | 2021-11-12 14:48:33.793 UTC | 2021-11-12 14:48:33.793 UTC | null | 15,497,888 | null | 391,104 | null | 1 | 31 | regex|pcre | 25,946 | <p>PCRE does not support the <code>\uXXXX</code> syntax. Use <code>\x{XXXX}</code> instead. See <a href="http://www.regular-expressions.info/unicode.html" rel="noreferrer">here</a>.</p>
<p>Your <code>\u2e80-\u9fff</code> range is also equivalent to</p>
<p><code>\p{InCJK_Radicals_Supplement}\p{InKangxi_Radicals}\p{InIdeographic_Description_Characters}\p{InCJK_Symbols_and_Punctuation}\p{InHiragana}\p{InKatakana}\p{InBopomofo}\p{InHangul_Compatibility_Jamo}\p{InKanbun}\p{InBopomofo_Extended}\p{InKatakana_Phonetic_Extensions}\p{InEnclosed_CJK_Letters_and_Months}\p{InCJK_Compatibility}\p{InCJK_Unified_Ideographs_Extension_A}\p{InYijing_Hexagram_Symbols}\p{InCJK_Unified_Ideographs}</code></p>
<p>Don't forget to add the <code>u</code> modifier (<code>/regex here/u</code>) if you're dealing with UTF-8. If you're dealing with another multi-byte encoding, you must first <a href="http://php.net/mb_convert_encoding" rel="noreferrer">convert</a> it to UTF-8.</p> |
9,311,538 | How to make non-breaking spaces (ties) in Org-mode that exports properly to LaTeX | <p>In (La)TeX non-breaking spaces are called ties and they are made by <code>~</code>. Ties are for instance used after abbreviations so that there is no line break directly after them and so that dots ending abbrevations are not treated as ending sentences. The latter use is important because standardly LaTeX puts a longer space after dots than between words.</p>
<p>When exporting from Org-mode to LaTeX <code>~</code> is treated as an explicit character and not as a tie. Ignoring the use of non-breaking spaces is not an alternative because it leads to the wrong spacing (see the second sentence in the example above). One alternative is to force Org-mode to treat <code>~</code> as LaTeX with <a href="http://orgmode.org/manual/Quoting-LaTeX-code.html#Quoting-LaTeX-code"><code>#+BEGIN_LaTeX ~ #+END_LaTeX</code></a> but it is verbose and export to other formats breaks. Finally, using UTF-8 non-breaking spaces, as suggested in <a href="http://comments.gmane.org/gmane.emacs.orgmode/24716">http://comments.gmane.org/gmane.emacs.orgmode/24716</a>, does not work because LaTeX does not treat it as a space. So, how can I use non-breaking spaces in Org-mode that are properly exported to LaTeX?</p>
<p>Here is an example to clarify. The first sentence fails because <code>~</code> is treated as an explicit character. The second sentence fails, obviously, because the last dot is treated as ending a sentence by LaTeX. The third sentence exports properly but it is verbose and breaks export to other formats. The fourth line (separated by an UTF-8 non-breaking space which is inserted by <kbd>C-x 8 Space</kbd>) fails because it is not treated as a space by LaTeX:</p>
<pre><code>#+title:Title
e.g.~example
e.g. example
#+BEGIN_LaTeX
e.g.~example
#+END_LaTeX
e.g. example
</code></pre>
<p>This exports (<kbd>C-x C-e L</kbd>) to the following LaTeX code:</p>
<pre class="lang-latex prettyprint-override"><code>e.g.\~{}example
e.g. example
e.g.~example
e.g. example
</code></pre>
<p>Which renders as:</p>
<p><img src="https://i.stack.imgur.com/1reJH.png" alt="LaTeX rendered"></p>
<p>I am running Org-mode 7.6 in Emacs 23.3.1.</p> | 16,176,740 | 5 | 2 | null | 2012-02-16 12:48:52.16 UTC | 5 | 2022-05-20 09:34:25.5 UTC | 2012-03-25 19:51:13.217 UTC | null | 246,246 | null | 789,593 | null | 1 | 30 | emacs|latex|whitespace|org-mode | 8,651 | <p>On <a href="http://orgmode.org/manual/Special-symbols.html">http://orgmode.org/manual/Special-symbols.html</a> I found the solution to the double spacing problem:</p>
<p>Org</p>
<pre><code>e.g.\nbsp{}example
</code></pre>
<p>LaTeX</p>
<pre><code>e.g.~example
</code></pre> |
29,769,181 | Count the number of folders in a directory and subdirectories | <p>I've got a script that will accurately tell me how many files are in a directory, and the subdirectories within. However, I'm also looking into identify how many folders there are within the same directory and its subdirectories...</p>
<p>My current script:</p>
<pre><code>import os, getpass
from os.path import join, getsize
user = 'Copy of ' + getpass.getuser()
path = "C://Documents and Settings//" + user + "./"
folder_counter = sum([len(folder) for r, d, folder in os.walk(path)])
file_counter = sum([len(files) for r, d, files in os.walk(path)])
print ' [*] ' + str(file_counter) + ' Files were found and ' + str(folder_counter) + ' folders'
</code></pre>
<p>This code gives me the print out of: <code>[*] 147 Files were found and 147 folders</code>.</p>
<p>Meaning that the <code>folder_counter</code> isn't counting the right elements. How can I correct this so the <code>folder_counter</code> is correct?</p> | 29,769,297 | 4 | 3 | null | 2015-04-21 10:11:16.507 UTC | 4 | 2022-08-16 07:35:06.943 UTC | 2015-04-21 10:18:32.233 UTC | null | 3,001,761 | null | 4,641,623 | null | 1 | 7 | python|python-2.7|directory | 40,887 | <p>I think you want something like:</p>
<pre><code>import os
files = folders = 0
for _, dirnames, filenames in os.walk(path):
# ^ this idiom means "we won't be using this value"
files += len(filenames)
folders += len(dirnames)
print "{:,} files, {:,} folders".format(files, folders)
</code></pre>
<p>Note that this only iterates over <code>os.walk</code> once, which will make it much quicker on paths containing lots of files and directories. Running it on my Python directory gives me:</p>
<pre><code>30,183 files, 2,074 folders
</code></pre>
<p>which exactly matches what the Windows folder properties view tells me.</p>
<hr>
<p>Note that your current code calculates the same number twice because the <em>only change</em> is renaming one of the returned values from the call to <code>os.walk</code>:</p>
<pre><code>folder_counter = sum([len(folder) for r, d, folder in os.walk(path)])
# ^ here # ^ and here
file_counter = sum([len(files) for r, d, files in os.walk(path)])
# ^ vs. here # ^ and here
</code></pre>
<p>Despite that name change, you're counting the same value (i.e. in both it's the third of the three returned values that you're using)! Python functions <strong>do not know</strong> what names (if any at all; you could do <code>print list(os.walk(path))</code>, for example) the values they return will be assigned to, and their behaviour certainly won't change because of it. Per <a href="https://docs.python.org/2/library/os.html#os.walk" rel="noreferrer">the documentation</a>, <code>os.walk</code> returns a three-tuple <code>(dirpath, dirnames, filenames)</code>, and the names you use for that, e.g. whether:</p>
<pre><code>for foo, bar, baz in os.walk(...):
</code></pre>
<p>or:</p>
<pre><code>for all_three in os.walk(..):
</code></pre>
<p>won't change that.</p> |
16,316,940 | How to resolve $q.all promises in Jasmine unit tests? | <p>My controller has code like below:</p>
<pre class="lang-js prettyprint-override"><code>$q.all([qService.getData($scope.id), dService.getData(), qTService.get()])
.then(function (allData) {
$scope.data1 = allData[0];
$scope.data2 = allData[1];
$scope.data3 = allData[2];
});
</code></pre>
<p>And in my unit tests i am doing something like this:</p>
<pre class="lang-js prettyprint-override"><code>beforeEach(inject(function($rootScope, $q, $location){// and other dependencies...
qServiceSpy = spyOn(_qService, 'getData').andCallFake(function () {
var data1 = {
id: 1,
sellingProperty: 1,
};
var d = $q.defer();
d.resolve(data1);
return d.promise;
});
dServiceSpy = spyOn(_dService, 'getData').andCallFake(function () {
var data2 = [{ "id": "1", "anotherProp": 123 }];
var d = $q.defer();
d.resolve(data2);
return d.promise;
});
qTServiceSpy = spyOn(_qTService, 'get').andCallFake(function () {
var data3 = [{ id: 0, name: 'Rahul' }];
var d = $q.defer();
d.resolve(data3);
return d.promise;
});
rootScope = $rootScope;
});
</code></pre>
<p>Now in my test i am checking if services are called and the data1, data2 are not undefined..</p>
<pre class="lang-js prettyprint-override"><code>it('check if qService' got called, function() {
expect(scope.data1).toBeUndefined();
rootScope.$digest();
expect(_quoteService.getQuote).toHaveBeenCalled();
});
it('check if "data1" is defined', function () {
expect(scope.data1).toBeUndefined();
rootScope.$digest();
expect(scope.data1).toBeDefined();
});
</code></pre>
<p>my problem is, this was working fine until i replaced my individual service calls in controller with q.all and in tests <code>scope.$apply</code> with <code>rootScope.$digest</code>. With q.all and <code>rootScope.$digest</code> (tried using <code>scope.$apply</code> as well) both tests fails with error:</p>
<blockquote>
<p>10 $digest() iterations reached. Aborting!</p>
</blockquote>
<p>if i remove <code>rootScope.$digest</code> then the promises never get resolves and tests fails saying </p>
<blockquote>
<p>expected undefined to be defined.</p>
</blockquote>
<p>Any help how should i unit tests code with <code>q.all</code>?</p>
<p>came across <a href="https://groups.google.com/forum/#!msg/angular/icQGGKZy-Is/zwnmZZdfT-0J" rel="noreferrer">this post</a></p>
<p>But that also doesn't help as i am already trying to use <code>$digest</code>.</p> | 18,107,038 | 1 | 0 | null | 2013-05-01 11:03:51.87 UTC | 7 | 2016-09-22 12:01:41.42 UTC | 2016-09-22 12:01:41.42 UTC | null | 863,110 | null | 1,421,196 | null | 1 | 31 | angularjs|unit-testing|jasmine|karma-runner|jasmine-jquery | 26,305 | <p>You can try putting <code>$rootScope.$apply()</code> in an <code>afterEach()</code> callback function. Promises resolve on <code>$apply()</code> in Angular.</p>
<pre><code>afterEach(function(){
rootScope.$apply();
});
</code></pre> |
16,491,973 | Using RegEx in JSON Schema | <p>Trying to write a JSON schema that uses RegEx to validate a value of an item.</p>
<p>Have an item named <strong>progBinaryName</strong> whose value should adhrere to this RegEx string <code>"^[A-Za-z0-9 -_]+_Prog\\.(exe|EXE)$"</code>.</p>
<p>Can not find any tutorials or examples that actually explain the use of RegEx in a JSON schema.</p>
<p>Any help/info would be GREATLY appreciated!</p>
<p>Thanks,
D</p>
<p>JSON SCHEMA</p>
<pre><code>{
"name": "string",
"properties": {
"progName": {
"type": "string",
"description": "Program Name",
"required": true
},
"ID": {
"type": "string",
"description": "Identifier",
"required": true
},
"progVer": {
"type": "string",
"description": "Version number",
"required": true
},
"progBinaryName": {
"type": "string",
"description": "Actual name of binary",
"patternProperties": {
"progBinaryName": "^[A-Za-z0-9 -_]+_Prog\\.(exe|EXE)$"
},
"required": true
}
}
}
</code></pre>
<p>ERRORS:</p>
<p>Warning! Better check your JSON.</p>
<p>Instance is not a required type - <a href="http://json-schema.org/draft-03/hyper-schema#" rel="noreferrer">http://json-schema.org/draft-03/hyper-schema#</a></p>
<hr>
<p>Schema is valid JSON, but not a valid schema.</p>
<hr>
<p>Validation results: failure</p>
<pre><code>[ {
"level" : "warning",
"schema" : {
"loadingURI" : "#",
"pointer" : ""
},
"domain" : "syntax",
"message" : "unknown keyword(s) found; ignored",
"ignored" : [ "name" ]
}, {
"level" : "error",
"domain" : "syntax",
"schema" : {
"loadingURI" : "#",
"pointer" : "/properties/ID"
},
"keyword" : "required",
"message" : "value has incorrect type",
"expected" : [ "array" ],
"found" : "boolean"
}, {
"level" : "error",
"domain" : "syntax",
"schema" : {
"loadingURI" : "#",
"pointer" : "/properties/progBinaryName"
},
"keyword" : "required",
"message" : "value has incorrect type",
"expected" : [ "array" ],
"found" : "boolean"
}, {
"level" : "error",
"schema" : {
"loadingURI" : "#",
"pointer" : "/properties/progBinaryName/patternProperties/progBinaryName"
},
"domain" : "syntax",
"message" : "JSON value is not a JSON Schema: not an object",
"found" : "string"
}, {
"level" : "error",
"domain" : "syntax",
"schema" : {
"loadingURI" : "#",
"pointer" : "/properties/progName"
},
"keyword" : "required",
"message" : "value has incorrect type",
"expected" : [ "array" ],
"found" : "boolean"
}, {
"level" : "error",
"domain" : "syntax",
"schema" : {
"loadingURI" : "#",
"pointer" : "/properties/progVer"
},
"keyword" : "required",
"message" : "value has incorrect type",
"expected" : [ "array" ],
"found" : "boolean"
} ]
</code></pre>
<hr>
<pre><code>Problem with schema#/properties/progBinaryName/patternProperties/progBinaryName : Instance is not a required type
Reported by http://json-schema.org/draft-03/hyper-schema#
Attribute "type" (["object"])
</code></pre> | 17,723,546 | 2 | 6 | null | 2013-05-10 22:59:47.473 UTC | 1 | 2021-01-11 19:50:47.513 UTC | 2015-10-21 13:56:33.63 UTC | null | 627,727 | null | 1,375,924 | null | 1 | 38 | regex|json|schema|jsonschema | 62,254 | <p>To test a string value (not a property name) against a RegEx, you should use the <code>"pattern"</code> keyword:</p>
<pre><code>{
"type": "object",
"properties": {
"progBinaryName": {
"type": "string",
"pattern": "^[A-Za-z0-9 -_]+_Prog\\.(exe|EXE)$"
}
}
}
</code></pre>
<p>P.S. - if you want the pattern to match the <em>key</em> for the property (not the value), then you should use <code>"patternProperties"</code> (it's like <code>"properties"</code>, but the key is a RegEx).</p> |
16,247,944 | Invalid column count in CSV input on line 1 Error | <p>I'm trying to get a ".csv" file onto an SQL database with phpMyAdmin. However, whenever I import it, I get the error: Invalid column count in CSV input on line 1.
I've spent all day playing around with different options to try and get it to work but with no avail. There are exactly 47 columns in my .csv file. I have created 47 columns in my SQL table. The names however aren't exactly the same as the ones in the file. Whenever I import, it keeps giving me that error.
Any help would be greatly appreciated!
~Carpetfizz
One thing I thought might be causing the problem was that the first column isn't named anything in my excel document. Could this be causing an issue?</p>
<p>EDIT 12:30AM: phpMyAdmin is already the latest version available, via (apt-get install phpmyadmin) (phpmyadmin is already latest version)</p>
<p><img src="https://i.stack.imgur.com/2Qxee.png" alt="Space in A1"></p>
<p><a href="http://pastebin.com/jTf67nsj" rel="noreferrer">Here</a> is the .csv file, if that helps.</p> | 16,253,846 | 14 | 10 | null | 2013-04-27 03:12:12.847 UTC | 6 | 2021-10-05 16:38:06.893 UTC | 2013-04-27 07:30:58.69 UTC | null | 896,112 | null | 896,112 | null | 1 | 54 | php|mysql|excel|csv | 196,047 | <p>Fixed! I basically just selected "Import" without even making a table myself. phpMyAdmin created the table for me, with all the right column names, from the original document. </p> |
29,303,164 | Get all months name from year in moment.js | <p>I want to get all months name from year in moment.js </p>
<p>if the year is <code>2011</code>, then i want to all months name in momentjs </p>
<p>i have tried this below code, but it's not working for me.</p>
<pre><code>var xxx = moment().months(2011);
</code></pre>
<p>Showing result is </p>
<p><img src="https://i.stack.imgur.com/q8JzL.jpg" alt="enter image description here"></p>
<p>also i have tried <code>xxx.months()</code>, but it's return result is <code>7</code> </p>
<p>but i want <code>jan,feb,mar,......dec</code>. <strong>hmm What can i do?</strong> </p> | 29,303,336 | 9 | 5 | null | 2015-03-27 14:31:53.37 UTC | 7 | 2019-12-23 08:52:36.237 UTC | 2015-03-27 14:43:55.62 UTC | null | 333,777 | null | 2,218,635 | null | 1 | 34 | javascript|momentjs | 78,773 | <p>There happens to be a function for that:</p>
<pre><code>moment.monthsShort()
// ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
</code></pre>
<p>Or the same using manual formatting:</p>
<pre><code>Array.apply(0, Array(12)).map(function(_,i){return moment().month(i).format('MMM')})
</code></pre>
<p>I guess you want to display all names utilizing Moment.js locale data, which is a reasonable approach.</p> |
17,192,916 | Django: Get database object value in template using Ajax | <p>I want to fetch database object depending on user selection. I know one possible solution could be Ajax, but I don't know how to get about it. Here is the code:</p>
<p><strong>view.py:</strong></p>
<pre><code>def automation(request):
//some code
car = CAR.objects.get(ida_name='honda')
model = car.model_set.all()
//some code
</code></pre>
<p><strong>template.html:</strong></p>
<pre><code>Select CAR: <select id="car" name="car">
{% for car in car_list %}
<option value="{{ car.id }}" id="{{ car.id }}">{{ car.car_name }}</option>
{% endfor %}
</select>
Select car model: <select id="model" name="model">
{% for model in car.model_set.all %}
<option value="{{ forloop.counter }}">{{ model.model_name }}</option>
{% endfor %}
</select>
</code></pre>
<p>Here, I want to pass a name eg.'honda' from my template (as soon as user selects it in drop down) to my view.py which would then fetch the corresponding object and return the result back to my template in 'model' drop down list. (So, basically the car model list refreshes when user selects any car from the car drop down list)</p>
<p><strong>Note:</strong> Model is in many-to-many relationship with Car in models.py</p>
<p>I am stuck up here for quite long and any help would be really appreciated.</p> | 17,193,263 | 2 | 0 | null | 2013-06-19 13:45:41.317 UTC | 9 | 2016-09-19 16:16:44.267 UTC | 2013-06-20 19:44:18.073 UTC | null | 2,150,258 | null | 2,150,258 | null | 1 | 6 | ajax|django|jquery | 14,321 | <p>You can use AJAX to call back to your Django code and return the name of your car:</p>
<p>template.html</p>
<pre><code>$(document).ready(function () {
$(document).on("click",'.car_add', function() {
$car_id = $(this).attr('id')
$.ajax({
type: "POST",
// This is the dictionary you are SENDING to your Django code.
// We are sending the 'action':add_car and the 'id: $car_id
// which is a variable that contains what car the user selected
data: { action: "add_car", id: $car_id },
success: function(data){
// This will execute when where Django code returns a dictionary
// called 'data' back to us.
$("#car").html("<strong>"+data.car+"</strong>");
}
});
});
});
</code></pre>
<p>views.py</p>
<pre><code>def post(self,request, *args, **kwargs):
if self.request.is_ajax():
return self.ajax(request)
def ajax(self, request):
response_dict= {
'success': True,
}
action = request.POST.get('action','')
if action == 'add_car':
car_id = request.POST.get('id','')
if hasattr(self, action):
response_dict = getattr(self, action)(request)
car = CAR.objects.get(ida_name='car_id')
response_dict = {
'car_name':car.name
}
return HttpResponse(simplejson.dumps(response_dict),
mimetype='application/json')
</code></pre>
<p>So in summary, here is what you're doing:</p>
<ul>
<li>Sending the 'id' of the car back to Django through Ajax.</li>
<li>Django 'posts' to itself, realizes it is an AJAX call and calls the AJAX function</li>
<li>Django see's that the action is 'add_car' and executes if statement</li>
<li>Django queries the DB using the id you sent it, returning a car</li>
<li>Django sends that data back to the page as a JSON object (a dictionary in this case)</li>
<li>JQuery updates the page using the passed information.</li>
</ul>
<p>If you want to see a clear cut example, please see this <a href="http://www.devinterface.com/blog/en/2011/02/how-to-implement-two-dropdowns-dependent-on-each-other-using-django-and-jquery/" rel="nofollow">Link</a></p> |
17,326,969 | Reading Integer user input in DataInputStream in java? | <p>I am trying to get input from user using <code>DataInputStream</code>. But this displays some junk integer value instead of the given value.</p>
<p>Here is the code:</p>
<pre><code>import java.io.*;
public class Sequence {
public static void main(String[] args) throws IOException {
DataInputStream dis = new DataInputStream(System.in);
String str="Enter your Age :";
System.out.print(str);
int i=dis.readInt();
System.out.println((int)i);
}
}
</code></pre>
<p>And the output is </p>
<blockquote>
<p>Enter your Age :12</p>
<p>825363722</p>
</blockquote>
<p>Why am I getting this junk value and how to correct the error?</p> | 17,327,033 | 4 | 0 | null | 2013-06-26 17:43:55.67 UTC | 1 | 2021-02-09 10:38:05.56 UTC | 2020-06-11 07:06:31.683 UTC | null | 10,251,345 | null | 1,709,984 | null | 1 | 9 | java|datainputstream | 38,446 | <p>The problem is that <a href="http://docs.oracle.com/javase/6/docs/api/java/io/DataInput.html#readInt%28%29"><code>readInt</code></a> does not behave as you might expect. It is not reading a string and convert the string to a number; it reads the input as *<em>bytes</em>:</p>
<blockquote>
<p>Reads four input bytes and returns an int value. Let a-d be the first through fourth bytes read. The value returned is:</p>
<pre><code>(((a & 0xff) << 24) | ((b & 0xff) << 16) |
((c & 0xff) << 8) | (d & 0xff))
</code></pre>
<p>This method is suitable for reading bytes written by the writeInt method of interface DataOutput.</p>
</blockquote>
<p>In this case, if you are in Windows and input <code>12</code> then enter, the bytes are:</p>
<ul>
<li>49 - '1'</li>
<li>50 - '2'</li>
<li>13 - carriage return</li>
<li>10 - line feed</li>
</ul>
<p>Do the math, 49 * 2 ^ 24 + 50 * 2 ^ 16 + 13 * 2 ^ 8 + 10 and you get 825363722.</p>
<p>If you want a simple method to read input, checkout <code>Scanner</code> and see if it is what you need.</p> |
17,616,702 | Difficulty fitting gamma distribution with R | <p>I am attempting to estimate parameters for a gamma distribution fit to ecological density (i.e. biomass per area) data. I have been using the fitdistr() command from the MASS package in R (version 3.0.0 : x86_64-w64-mingw32/x64 (64-bit)). This is a maximum likelihood estimation command for distributional parameters.</p>
<p>The vectors of data are quite large, but summary statistics are as follows:</p>
<blockquote>
<p>Min. = 0; 1st Qu. = 87.67; Median = 199.5; Mean = 1255; Variance =
2.79E+07; 3rd Qu. = 385.6; Max. = 33880</p>
</blockquote>
<p>The code I am using to run the MLE procedure is:</p>
<pre><code>gdist <- fitdistr(data, dgamma,
start=list(shape=1, scale=1/(mean(data))),lower=c(1,0.1))
</code></pre>
<p>R is giving me the following error:</p>
<blockquote>
<p>Error in optim(x = c(6.46791148085828, 4060.54750836902,
99.6201565968665, : non-finite finite-difference value [1]</p>
</blockquote>
<p>Others who have experienced this type of issue and have turned to stackoverflow for help seem to have found the solution in adding the "lower=" argument to their code, and/or removing zeros. I find that R will provide parameters for a fit if I remove the zero observations, but I was under the impression that gamma distributions covered the range 0 <= x > inf (Forbes et al. 2011. Statistical Distributions)?</p>
<p>Have I gotten the wrong impression regarding the range of the gamma distribution? Or is there some other issue I am missing regarding MLE (in which I am a novice).</p> | 17,617,035 | 1 | 0 | null | 2013-07-12 14:00:46.74 UTC | 10 | 2013-07-12 14:23:13.63 UTC | 2013-07-12 14:03:59.773 UTC | null | 324,364 | null | 2,508,617 | null | 1 | 11 | r | 13,929 | <p>Getting a rough estimate by the method of moments (matching up the mean=shape*scale and variance=shape*scale^2) we have</p>
<pre><code>mean <- 1255
var <- 2.79e7
shape = mean^2/var ## 0.056
scale = var/mean ## 22231
</code></pre>
<p>Now generate some data from this distribution:</p>
<pre><code>set.seed(101)
x = rgamma(1e4,shape,scale=scale)
summary(x)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.00 0.00 0.06 1258.00 98.26 110600.00
MASS::fitdistr(x,"gamma") ## error
</code></pre>
<p>I strongly suspect that the problem is that the underlying <code>optim</code> call assumes the parameters (shape and scale, or shape and rate) are of approximately the same magnitude, which they're not. You can get around this by scaling your data:</p>
<pre><code>(m <- MASS::fitdistr(x/2e4,"gamma")) ## works fine
## shape rate
## 0.0570282411 0.9067274280
## (0.0005855527) (0.0390939393)
</code></pre>
<p><code>fitdistr</code> gives a rate parameter rather than a scale parameter: to get back to the shape parameter you want, invert and re-scale ...</p>
<pre><code>1/coef(m)["rate"]*2e4 ## 22057
</code></pre>
<p>By the way, the fact that the quantiles of the simulated data don't match your data very well (e.g. median of <code>x</code>=0.06 vs a median of 199 in your data) suggest that your data might not fit a Gamma all that well -- e.g. there might be some outliers affecting the mean and variance more than the quantiles?</p>
<p>PS above I used the built-in 'gamma' estimator in <code>fitdistr</code> rather than using <code>dgamma</code>: with starting values based on the method of moments, and scaling the data by 2e4, this works (although it gives a warning about <code>NaNs produced</code> unless we specify <code>lower</code>)</p>
<pre><code> m2 <- MASS::fitdistr(x/2e4,dgamma,
start=list(shape=0.05,scale=1), lower=c(0.01,0.01))
</code></pre> |
21,513,706 | Getting the list of voices in speechSynthesis (Web Speech API) | <p>Following HTML shows empty array in console on first click:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<script>
function test(){
console.log(window.speechSynthesis.getVoices())
}
</script>
</head>
<body>
<a href="#" onclick="test()">Test</a>
</body>
</html>
</code></pre>
<p>In second click you will get the expected list.</p>
<p>If you add <code>onload</code> event to call this function (<code><body onload="test()"></code>), then you can get correct result on first click. Note that the first call on <code>onload</code> still doesn't work properly. It returns empty on page load but works afterward.</p>
<p><strong>Questions:</strong></p>
<p>Since it might be <a href="https://code.google.com/p/chromium/issues/detail?id=340160" rel="noreferrer">a bug</a> in beta version, I gave up on "Why" questions. </p>
<p>Now, the question is if you want to access <code>window.speechSynthesis</code> on page load:</p>
<ul>
<li>What is the best hack for this issue?</li>
<li>How can you make sure it will load <code>speechSynthesis</code>, on page load? </li>
</ul>
<p><strong>Background and tests:</strong></p>
<p>I was testing the new features in Web Speech API, then I got to this problem in my code:</p>
<pre><code><script type="text/javascript">
$(document).ready(function(){
// Browser support messages. (You might need Chrome 33.0 Beta)
if (!('speechSynthesis' in window)) {
alert("You don't have speechSynthesis");
}
var voices = window.speechSynthesis.getVoices();
console.log(voices) // []
$("#test").on('click', function(){
var voices = window.speechSynthesis.getVoices();
console.log(voices); // [SpeechSynthesisVoice, ...]
});
});
</script>
<a id="test" href="#">click here if 'ready()' didn't work</a>
</code></pre>
<p>My question was: why does <code>window.speechSynthesis.getVoices()</code> return empty array, after page is loaded and <code>onready</code> function is triggered? As you can see if you click on the link, same function returns an array of available voices of Chrome by <code>onclick</code> triger?</p>
<p>It seems Chrome loads <code>window.speechSynthesis</code> after the page load!</p>
<p>The problem is not in <code>ready</code> event. If I remove the line <code>var voice=...</code> from <code>ready</code> function, for first click it shows empty list in console. But the second click works fine.</p>
<p>It seems <code>window.speechSynthesis</code> needs more time to load after first call. You need to call it twice! But also, you need to wait and let it load before second call on <code>window.speechSynthesis</code>. For example, following code shows two empty arrays in console if you run it for first time:</p>
<pre><code>// First speechSynthesis call
var voices = window.speechSynthesis.getVoices();
console.log(voices);
// Second speechSynthesis call
voices = window.speechSynthesis.getVoices();
console.log(voices);
</code></pre> | 22,978,802 | 13 | 4 | null | 2014-02-02 17:25:55.14 UTC | 10 | 2022-06-08 16:37:47.347 UTC | 2019-11-25 02:49:03.187 UTC | null | 3,702,797 | null | 2,991,872 | null | 1 | 61 | dom-events|voice|speech-synthesis|webspeech-api | 38,302 | <p>According to <a href="https://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi-errata.html">Web Speech API Errata</a> (E11 2013-10-17), the voice list is loaded async to the page. An <code>onvoiceschanged</code> event is fired when they are loaded.</p>
<blockquote>
<p>voiceschanged: Fired when the contents of the SpeechSynthesisVoiceList, that the getVoices method will return, have changed. Examples include: server-side synthesis where the list is determined asynchronously, or when client-side voices are installed/uninstalled.</p>
</blockquote>
<p>So, the trick is to set your voice from the callback for that event listener:</p>
<pre><code>// wait on voices to be loaded before fetching list
window.speechSynthesis.onvoiceschanged = function() {
window.speechSynthesis.getVoices();
...
};
</code></pre> |
19,326,426 | Why doesn't the `href` attribute on the `<td>` element work? | <p>I've set up a <a href="http://jsfiddle.net/7aHDR/4/" rel="noreferrer">fiddle</a> with a table.</p>
<p>You see, Im trying to make a table where the user will hover and click the td to show an id. Check the fiddle out and you'll understand.</p>
<p>Now, When the user hovers Parent4, you may notice there's space on the table where there's no text and the user can't click it so the Child4 wont appear....</p>
<p>Now, is there any way I can make the space where there's no text clickable so it shows up child4?</p>
<p>I tried </p>
<pre><code><td ahref="#child4"> but didn't work...
</code></pre>
<p>////?EDIT As its a bit confusing...</p>
<p>I need you to see the fiddle.
You can see the cell for Parent4 is bigger than the text. So when the user hovers on the cell I want the text to change color and the cell to change color too + if the user clicks the cell Child4 won't appear because a cell is unclickable, so My question, how can I make the cell clickable to display Child4?</p>
<p>UPD:</p>
<p>I didn't update the fiddle, but it's now up to date.</p> | 19,326,453 | 8 | 6 | null | 2013-10-11 20:08:12.97 UTC | 6 | 2022-02-10 17:06:09.927 UTC | 2022-02-10 17:06:09.927 UTC | null | 247,696 | null | 2,766,367 | null | 1 | 27 | html|css | 104,290 | <p>The <code>href</code> property is designed for <a href="http://www.w3.org/TR/html5/text-level-semantics.html#the-a-element">anchor elements (<code><a/></code>)</a>. "ahref" as you've put should be <code><a href=""></code>. <code>a</code> is an element of its own, not a HTML attribute, and <code>href</code> is an attribute it accepts.</p>
<p>To make the text of a <code>td</code> clickable you can simply put an anchor within it:</p>
<pre><code><td>
<a href="#child4">My clickable text</a>
</td>
</code></pre>
<p><strong>Edit:</strong> To fix this now that the question has been added, simply add in the following CSS:</p>
<pre class="lang-css prettyprint-override"><code>td a {
display:block;
width:100%;
}
</code></pre>
<p>What this does is display the anchor tag as a block, allowing us to adjust the width, and then set the width to 100%, allowing it to fill the remaining space.</p>
<p><a href="http://jsfiddle.net/7aHDR/5/"><strong>Working JSFiddle</strong></a>.</p> |
17,250,786 | Rails: Submit button outside form_tag | <p>I'm using a button to perform processing in a group of selected check-boxes. The solution is based on RailsCast #165.</p>
<p>It's all working fine, but only if the <strong>submit_tag</strong> button is contained within the form (which is a table in my application). I'd like to place the submit button in the page header, but this breaks the connection to the form.</p>
<p>How can I place a submit button outside the body of the form?</p>
<pre><code><%= form_tag select_cosmics_path, method: :put do %>
<%= submit_tag "Accept Checked", :class => "btn btn-primary" %>
<table class="table table-striped">
.
.
<% @cosmics.each do |cosmic| %>
<tr>
<td><%= check_box_tag "cosmic_ids[]", cosmic.id %></td>
.
.
</tr>
<% end %>
</table>
<% end %>
</code></pre>
<p><strong>routes.rb</strong></p>
<pre><code>resources :cosmics do
collection do
put :select
end
end
</code></pre> | 31,135,134 | 3 | 3 | null | 2013-06-22 12:36:39.103 UTC | 9 | 2015-09-07 07:25:42.587 UTC | null | null | null | null | 993,592 | null | 1 | 31 | ruby-on-rails|forms | 14,019 | <p>While this question is old, I think it might be worth pointing out a better option that doesn't rely on JavaScript.</p>
<p>HTML5 introduced <code>form</code> as an attribute that can be applied to any form control and will bind it to a specific form based on its id - even if the control isn't nested inside the form tag. </p>
<p>Example:</p>
<pre><code><form id="my_sample_form">
...
</form>
<input type="submit" value="Submit" form="my_sample_form">
</code></pre>
<p>This submit button will submit the form with the id specified in its form attribute.</p>
<p>Furthermore this isn't limited to submit buttons, but instead works for any form control and allows you to submit form partials that are positioned all over the place.</p>
<p>In contrast to most JavaScript solutions, you will keep all native form features like submitting on enter/return.</p> |
17,384,020 | What do "transparent" and "opaque" mean when applied to programming concepts? | <p>The two pieces of programming jargon that cause me the most confusion are the words <strong><em>transparent</em></strong> and <strong><em>opaque</em></strong>. They are fairly commonly used, but I have never been fully clear on their meaning.</p>
<p>Google throws up plenty of examples of usage of the word 'transparent', like:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/2091378/fast-c-library-to-tranparently-manage-very-large-files">Fast 'C' library to tranparently manage very large files</a></li>
<li><a href="https://stackoverflow.com/questions/16289268/saving-application-data-transparently">Saving application data transparently</a></li>
<li><a href="https://stackoverflow.com/questions/16963693/adding-json-strings-transparently-to-a-map-list">Adding JSON Strings transparently to a map/list</a></li>
<li><a href="https://stackoverflow.com/questions/501891/how-do-i-use-gnu-screen-transparently">How do I use GNU Screen transparently</a></li>
</ul>
<p>and also a bunch of results for 'opaque', mostly relating to C concepts:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/2301454/what-defines-an-opaque-type-in-c-and-when-are-they-necessary-and-or-useful">What defines an opaque type in C, and when are they necessary and/or useful?</a></li>
<li><a href="https://stackoverflow.com/questions/7553750/what-is-an-opaque-pointer-in-c">What is an opaque pointer in C?</a></li>
<li><a href="https://stackoverflow.com/questions/3965279/opaque-c-structs-how-should-they-be-declared">Opaque C structs: how should they be declared?</a></li>
</ul>
<p>although I've also seen the word used in contexts unrelated to C.</p>
<p>Leaving aside their use within specific compound terms like "opaque pointer", what meanings do the words <em>transparent</em> and <em>opaque</em> have within the sphere of programming? Are they even each other's opposites, like the visual concepts they metaphorically allude to, or are they unrelated to each other?</p> | 17,385,138 | 1 | 0 | null | 2013-06-29 19:36:05.427 UTC | 9 | 2013-06-29 22:09:39.437 UTC | 2017-05-23 11:55:00.137 UTC | null | -1 | null | 1,709,587 | null | 1 | 50 | language-agnostic|terminology | 7,651 | <p>In the examples you give, <strong>transparent</strong> is being used to mean <em>hidden</em> in the sense of things taking place automatically behind the scenes (i.e. without the user of the code or the program having to interact).</p>
<p><strong>Opaque</strong> is also being used to mean <em>hidden</em>, which is perhaps where the confusion comes in. The term <em>opaque type</em> has a <a href="https://stackoverflow.com/questions/735131">specific meaning in C/C++</a>, where it refers to a type that has been declared but not yet defined.</p>
<p>In both cases, I think people are using these terms to express a lack of visibility. <strong>Transparent</strong> is used where something is present, but you can't see it. <strong>Opaque</strong> is used where something is present, but you can't see <em>inside</em> it to inspect its inner workings.</p> |
17,248,680 | 'await' works, but calling task.Result hangs/deadlocks | <p>I have the following four tests and the last one hangs when I run it. Why does this happen:</p>
<pre><code>[Test]
public void CheckOnceResultTest()
{
Assert.IsTrue(CheckStatus().Result);
}
[Test]
public async void CheckOnceAwaitTest()
{
Assert.IsTrue(await CheckStatus());
}
[Test]
public async void CheckStatusTwiceAwaitTest()
{
Assert.IsTrue(await CheckStatus());
Assert.IsTrue(await CheckStatus());
}
[Test]
public async void CheckStatusTwiceResultTest()
{
Assert.IsTrue(CheckStatus().Result); // This hangs
Assert.IsTrue(await CheckStatus());
}
private async Task<bool> CheckStatus()
{
var restClient = new RestClient(@"https://api.test.nordnet.se/next/1");
Task<IRestResponse<DummyServiceStatus>> restResponse = restClient.ExecuteTaskAsync<DummyServiceStatus>(new RestRequest(Method.GET));
IRestResponse<DummyServiceStatus> response = await restResponse;
return response.Data.SystemRunning;
}
</code></pre>
<hr />
<p>I use this extension method for <a href="http://restsharp.org/" rel="noreferrer">restsharp RestClient</a>:</p>
<pre><code>public static class RestClientExt
{
public static Task<IRestResponse<T>> ExecuteTaskAsync<T>(this RestClient client, IRestRequest request) where T : new()
{
var tcs = new TaskCompletionSource<IRestResponse<T>>();
RestRequestAsyncHandle asyncHandle = client.ExecuteAsync<T>(request, tcs.SetResult);
return tcs.Task;
}
}
</code></pre>
<pre><code>public class DummyServiceStatus
{
public string Message { get; set; }
public bool ValidVersion { get; set; }
public bool SystemRunning { get; set; }
public bool SkipPhrase { get; set; }
public long Timestamp { get; set; }
}
</code></pre>
<p>Why does the last test hang?</p> | 17,248,813 | 6 | 3 | null | 2013-06-22 08:10:58.107 UTC | 56 | 2021-02-08 09:39:34.51 UTC | 2020-07-28 22:12:29.23 UTC | null | 63,550 | null | 1,069,200 | null | 1 | 148 | c#|nunit|task|deadlock|async-await | 85,818 | <p>You're running into the standard deadlock situation that I describe <a href="http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html" rel="noreferrer">on my blog</a> and <a href="http://msdn.microsoft.com/en-us/magazine/jj991977.aspx" rel="noreferrer">in an MSDN article</a>: the <code>async</code> method is attempting to schedule its continuation onto a thread that is being blocked by the call to <code>Result</code>.</p>
<p>In this case, your <code>SynchronizationContext</code> is the one used by NUnit to execute <code>async void</code> test methods. I would try using <code>async Task</code> test methods instead.</p> |
23,208,674 | Add new attribute dynamically to the existing JSON array in Node | <p>I need to add an attribute which doesn't exist in the current JSON. The json object looks like below.</p>
<pre><code>var jsonObj = {
"result" : "OK",
"data" : []
};
</code></pre>
<p>And I want to add temperature inside 'data'. I could do it like below.</p>
<pre><code>jsonObj.data.push( {temperature : {}} );
</code></pre>
<p>And then, I want to add 'home', 'work' inside 'temperature'. The result would be like below.</p>
<pre><code>{
"result" : "OK",
"data" : [
{ "temperature" : {
"home" : 24,
"work" : 20 } }
]
};
</code></pre>
<p>How could I do this? I succeeded to insert 'temperature' inside 'data', but couldn't add 'home' & 'work' inside temperature. There could be more inside the 'temperature' so it needs to be enclosed with {}. </p> | 23,208,699 | 2 | 4 | null | 2014-04-22 01:10:51.113 UTC | 3 | 2015-10-29 04:29:43.193 UTC | null | null | null | null | 3,126,683 | null | 1 | 5 | javascript|json|node.js|attributes | 58,451 | <p>How about this?</p>
<pre><code>var temperature = { temperature: { home: 24, work: 20 }};
jsonObj.data.push(temperature);
</code></pre>
<p>I can't tell if doing it in two steps is important by how your question is structured, but you <em>could</em> add the home and work properties later by indexing into the array, like this:</p>
<pre><code>jsonObj.data.push({ temperature: { }});
jsonObj.data[0].temperature.home = 24;
jsonObj.data[0].temperature.work = 20;
</code></pre>
<p>But, that's not a great idea since it depends on the array index to find the temperature object. If that's a requirement, it would be better to do something like loop through the <code>data</code> array to find the object you're interested in conclusively.</p>
<p>Edit:</p>
<p>An example of looping through to locate the temperature object would go something like this:</p>
<pre><code>for (var i = 0; i < jsonObj.data.length; i++) {
if (jsonObj.data[i].temperature) {
break;
}
}
jsonObj.data[i].temperature.home = 24;
jsonObj.data[i].temperature.work = 20;
</code></pre>
<p>Edit:</p>
<p>If which particular property you'll be interested in is unknown at development time, you can use bracket syntax to vary that:</p>
<pre><code>for (var i = 0; i < jsonObj.data.length; i++) {
if (jsonObj.data[i]['temperature']) {
break;
}
}
jsonObj.data[i]['temperature'].home = 24;
jsonObj.data[i]['temperature'].work = 20;
</code></pre>
<p>Which means you could use a variable there instead of hard coding it:</p>
<pre><code>var target = 'temperature';
for (var i = 0; i < jsonObj.data.length; i++) {
if (jsonObj.data[i][target]) {
break;
}
}
jsonObj.data[i][target].home = 24;
jsonObj.data[i][target].work = 20;
</code></pre> |
5,472,160 | Which should I be using: urlparse or urlsplit? | <p>Which <a href="http://docs.python.org/py3k/library/urllib.parse.html" rel="noreferrer">URL parsing function pair</a> should I be using and why? </p>
<ul>
<li><a href="http://docs.python.org/py3k/library/urllib.parse.html#urllib.parse.urlparse" rel="noreferrer"><code>urlparse</code></a> and <a href="http://docs.python.org/py3k/library/urllib.parse.html#urllib.parse.urlunparse" rel="noreferrer"><code>urlunparse</code></a>, or</li>
<li><a href="http://docs.python.org/py3k/library/urllib.parse.html#urllib.parse.urlsplit" rel="noreferrer"><code>urlsplit</code></a> and <a href="http://docs.python.org/py3k/library/urllib.parse.html#urllib.parse.urlunsplit" rel="noreferrer"><code>urlunsplit</code></a>?</li>
</ul> | 5,472,236 | 3 | 0 | null | 2011-03-29 12:02:51.777 UTC | 4 | 2020-08-06 18:36:03.75 UTC | null | null | null | null | 149,482 | null | 1 | 41 | python|urllib|urlparse|urlsplit | 14,666 | <p>Directly from <a href="http://docs.python.org/py3k/library/urllib.parse.html#urllib.parse.urlsplit" rel="noreferrer">the docs you linked yourself</a>:</p>
<blockquote>
<p><code>urllib.parse.urlsplit(urlstring, scheme='', allow_fragments=True)</code><br>
This is similar to <code>urlparse()</code>, but does not split the params from the URL. This should generally be used instead of <code>urlparse()</code> if the more recent URL syntax allowing parameters to be applied to each segment of the path portion of the URL (see RFC 2396) is wanted.</p>
</blockquote> |
25,893,421 | LINQ Select into Dictionary | <p>I'm trying to take a <code>Select</code> and project each elements into a <code>Dictionary<string, UdpReceiveResult></code>
I currently have a <code>Select</code> that just projects the value of a <code>Dictionary</code> to a list <code>tasks</code> of type <code>UdpReceiveResult</code>. <code>clients</code> is a dictionary of type <code>Dictionary<string, UdpClient></code>. I have</p>
<pre><code>var tasks = clients.Select(c => c.Value.ReceiveAsync()).OrderByCompletion();
</code></pre>
<p>I want to project the key and <code>ReceiveAsync()</code> result into a new <code>Dictionary</code>. The <code>OrderByCompletion</code> is from Nito.AsyncEx dll.</p> | 25,893,751 | 2 | 3 | null | 2014-09-17 14:32:12.097 UTC | 4 | 2022-06-14 21:11:36.203 UTC | 2022-06-14 21:11:36.203 UTC | null | 4,925,121 | null | 375,456 | null | 1 | 41 | c#|linq|dictionary | 42,075 | <p>Well, for starters, you'll need your result to also include the key:</p>
<pre><code>var tasks = clients.Select(async c => new
{
c.Key,
Value = await c.Value.ReceiveAsync(),
});
</code></pre>
<p>Then when the tasks finish you can put them in a dictionary:</p>
<pre><code>var results = await Task.WhenAll(tasks);
var dictionary = results.ToDictionary(
pair => pair.Key, pair => pair.Value);
</code></pre> |
9,481,497 | Understanding how D3.js binds data to nodes | <p>I'm reading through the D3.js documentation, and am finding it hard to understand <a href="https://github.com/mbostock/d3/wiki/Selections#wiki-data" rel="noreferrer">the <code>selection.data</code> method</a> from the documentation. </p>
<p>This is the example code given in the documentation:</p>
<pre><code>var matrix = [
[11975, 5871, 8916, 2868],
[ 1951, 10048, 2060, 6171],
[ 8010, 16145, 8090, 8045],
[ 1013, 990, 940, 6907]
];
var tr = d3.select("body").append("table").selectAll("tr")
.data(matrix)
.enter().append("tr");
var td = tr.selectAll("td")
.data(function(d) { return d; })
.enter().append("td")
.text(function(d) { return d; });
</code></pre>
<p>I understand most of this, but what is going on with the <code>.data(function(d) { return d; })</code> section of the <code>var td</code> statement?</p>
<p>My best guess is as follows:</p>
<ul>
<li>The <code>var tr</code> statement has bound a four-element array to each tr node</li>
<li>The <code>var td</code> statement then uses that four-element array as its data, somehow</li>
</ul>
<p>But how does <code>.data(function(d) { return d; })</code> actually get that data, and what does it return? </p> | 9,507,615 | 3 | 3 | null | 2012-02-28 11:59:58.407 UTC | 30 | 2016-05-25 21:57:42.843 UTC | 2014-01-07 11:55:29.347 UTC | null | 3,052,751 | null | 806,539 | null | 1 | 79 | javascript|d3.js|html-table | 60,748 | <p>When you write:</p>
<pre><code>….data(someArray).enter().append('foo');
</code></pre>
<p>D3 creates a bunch of <code><foo></code> elements, one for each entry in the array. More importantly, it also associates the data for each entry in the array with that DOM element, as a <code>__data__</code> property.</p>
<p>Try this:</p>
<pre><code>var data = [ {msg:"Hello",cats:42}, {msg:"World",cats:17} ];
d3.select("body").selectAll("q").data(data).enter().append("q");
console.log( document.querySelector('q').__data__ );
</code></pre>
<p>What you will see (in the console) is the object <code>{msg:"Hello",cats:42}</code>, since that was associated with the first created <code>q</code> element.</p>
<p>If you later do:</p>
<pre><code>d3.selectAll('q').data(function(d){
// stuff
});
</code></pre>
<p>the value of <code>d</code> turns out to be that <code>__data__</code> property. (At this point it's up to you to ensure that you replace <code>// stuff</code> with code that returns a new array of values.)</p>
<p><a href="http://phrogz.net/js/d3-playground/#MultiBars_HTML" rel="noreferrer">Here's another example</a> showing the data bound to the HTML element and the ability to re-bind subsets of data on lower elements:</p>
<p> <img src="https://i.stack.imgur.com/7DxEa.png" alt="no description"></p> |
18,542,032 | Optional dependencies in AngularJS | <p>I'm trying to implement a controller in AngularJS which is used across multiple pages. It makes use of some services. Some of them are loaded on all pages, some - not. I mean it is defined in different files, and these files are loaded independently. But if I do not load these services on all pages I got error:</p>
<pre><code>Error: Unknown provider: firstOtionalServiceProvider <- firstOtionalService
</code></pre>
<p>So, I need to load scripts on all pages. Can I declare dependency as optional in Angular? E.g:</p>
<pre><code>myApp.controller('MyController', ['$scope', 'firstRequiredService', 'secondRequiredService', 'optional:firstOptionalService', 'optional:secondOptionalService', function($scope, firstRequiredService, secondRequiredService, firstOptionalService, secondOptionalSerivce){
// No need to check, as firstRequiredService must not be null
firstRequiredService.alwaysDefined();
// If the dependency is not resolved i want Angular to set null as argument and check
if (firstOptionalService) {
firstOptionalService.mayBeUndefinedSoCheckNull();
}
}]);
</code></pre> | 18,542,095 | 5 | 0 | null | 2013-08-30 21:56:39.86 UTC | 13 | 2017-01-27 12:41:33.937 UTC | 2016-06-23 04:38:00.6 UTC | null | 2,333,214 | null | 2,734,233 | null | 1 | 53 | javascript|angularjs|dependency-injection|optional-parameters | 23,190 | <p>No, Angular does not yet support optional dependencies out of the box. You'd better put all your dependencies into a module and load it as one Javascript file. If you need another set of dependencies - consider creating another module in another JS and putting all common dependencies to common JS.</p>
<p>However, behavior you've described can be achieved with <a href="http://docs.angularjs.org/api/AUTO.$injector" rel="noreferrer"><code>$injector</code> service</a>. You simply inject <code>$injector</code> instead of all your dependencies to a controller and pull dependencies from it manually, checking if they exist. That's it:</p>
<p><em>index.html:</em></p>
<pre><code><!DOCTYPE html>
<html data-ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="app.js"></script>
<script src="1.js"></script>
<script src="2.js"></script>
<title>1</title>
</head>
<body data-ng-controller="DemoController">
</body>
</html>
</code></pre>
<p><em>app.js:</em></p>
<pre><code>var myApp = angular.module('myApp', []);
myApp.service('commonService', function(){
this.action = function(){
console.log('Common service is loaded');
}
});
myApp.controller('DemoController', ['$scope', '$injector', function($scope, $injector){
var common;
var first;
var second;
try{
common = $injector.get('commonService');
console.log('Injector has common service!');
}catch(e){
console.log('Injector does not have common service!');
}
try{
first = $injector.get('firstService');
console.log('Injector has first service!');
}catch(e){
console.log('Injector does not have first service!');
}
try{
second = $injector.get('secondService');
console.log('Injector has second service!');
}catch(e){
console.log('Injector does not have second service!');
}
if(common){
common.action();
}
if(first){
first.action();
}
if(second){
second.action();
}
}]);
</code></pre>
<p><em>1.js:</em></p>
<pre><code>myApp.service('firstService', function(){
this.action = function(){
console.log('First service is loaded');
}
});
</code></pre>
<p><em>2.js:</em></p>
<pre><code>myApp.service('secondService', function(){
this.action = function(){
console.log('Second service is loaded');
}
});
</code></pre>
<p>See it live in <a href="http://plnkr.co/edit/5y3et8Wm76tokCyuDtR0?p=catalogue" rel="noreferrer">this plunk</a>! Try to play with <code><script></code> tags and watch for console output.</p>
<p>P.S. And, as @Problematic said, you can use <code>$injector.has()</code>, starting from AngularJS 1.1.5.</p> |
15,089,556 | CSS Center a Text Box | <p>Here is the registration box: </p>
<p><a href="http://technicaldebt.co.uk/fyp/register.php" rel="noreferrer">http://technicaldebt.co.uk/fyp/register.php</a></p>
<p>I am trying to get the box to center in the middle of the webpage. The CSS is attached below. Any help would be greatly appreciated.</p>
<pre><code>/*********************************************************************************/
/* Basic */
/*********************************************************************************/
*
{
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
body
{
background: #1e1e1e url(images/bg04.jpg) repeat;
font-family: 'Open Sans', sans-serif;
font-size: 11pt;
color: #7f7f7f;
}
form
{
}
form input,
form select,
form textarea
{
-webkit-appearance: none;
}
br.clear
{
clear: both;
}
p, ul, ol, dl, table
{
margin-bottom: 1em;
}
p
{
line-height: 1.7em;
}
a
{
color: #779c5b;
}
a:hover
{
text-decoration: none;
}
section,
article
{
margin-bottom: 3em;
}
section > :last-child,
article > :last-child
{
margin-bottom: 0;
}
section:last-child,
article:last-child
{
margin-bottom: 0;
}
.image
{
display: inline-block;
}
.image img
{
display: block;
width: 100%;
}
.image-full
{
display: block;
width: 100%;
}
.image-left
{
float: left;
margin: 0 2em 0 1em;
}
.image-border img
{
border-radius: 5px;
}
ul.style1
{
}
ul.style1 li
{
padding: 0.80em 0 0.75em 0;
border-top: 1px solid #e0e0e0;
}
ul.style1 a
{
text-decoration: underline;
color: #779c5b;
}
ul.style1 a:hover
{
text-decoration: none;
}
ul.style1 .image-left
{
margin-top: 0.50em;
margin-right: 1.50em;
margin-left: 0 !important;
}
ul.style1 .date
{
display: block;
margin: 0;
padding: 1em 0 0 0;
line-height: 0;
color: #047ab7;
}
ul.style1 .first
{
border-top: none;
}
ul.style2
{
}
ul.style2 li
{
overflow: hidden;
padding: 1.75em 0 1.75em 0;
border-top: 1px solid #e0e0e0;
}
ul.style2 p
{
margin: 0;
}
ul.style2 h3 {
padding: 0 0 0.50em 0;
font-size: 1.00em;
}
ul.style2 .image-left
{
margin-left: 0;
}
ul.style2 .first
{
border-top: none;
}
ol.style1
{
margin-left: 3em;
}
ol.style1 li
{
padding: 0.35em 0;
list-style: decimal;
}
.button
{
display: inline-block;
margin-top: 1em;
padding: 0.70em 1.5em;
border-radius: 5px;
background: #779c5b;
line-height: 1;
text-align: center;
text-decoration: none;
color: #FFFFFF;
transition: background-color .25s ease-in-out;
-moz-transition: background-color .25s ease-in-out;
-webkit-transition: background-color .25s ease-in-out;
}
.button:hover
{
background: #96b77c;
}
.button-style1
{
background: #222222;
}
.button-style1:hover
{
background: #2d2d2d;
}
.button-style2
{
margin-top: 0.50em;
padding: 1.75em 3.00em;
box-shadow: 5px 0 5px -5px rgba(0, 0, 0, 0.4), 0 6px 5px -5px rgba(0, 0, 0, 0.4), -5px 0 5px -5px rgba(0, 0, 0, 0.4);
line-height: 0.25em;
}
.button-style2:hover
{
background: #96b77c;
}
/* Assign these to ARTICLE tags */
.box
{
padding: 2.50em 2.50em;
background: #FFFFFF;
border: 1px solid #e0e0e0;
border-radius: 5px;
}
.box h2
{
padding: 0 0 0.40em 0;
letter-spacing: -0.03em;
font-size: 1.60em;
color: #0f0f0f;
}
.box .subtitle
{
padding: 0 0 0.30em 0;
font-size: 1.10em;
color: #5f6b8b;
}
.box-post
{
}
.box-featured-post
{
}
/* Assign these to SECTION tags */
.box-news
{
}
.box-tweets
{
}
.box-contact
{
}
/*********************************************************************************/
/* Wrappers */
/*********************************************************************************/
#wrapper
{
overflow: hidden;
background: url(images/bg01.jpg) repeat;
}
#wrapper-gradient
{
}
#header-wrapper
{
overflow: hidden;
background: url(images/gradient.svg);
background: -moz-linear-gradient(
center bottom,
rgba(0,0,0,0) 5%,
rgba(0,0,0,0.5) 100%
);
background: -webkit-gradient(
linear,
left bottom,
left top,
color-stop(0.0, rgba(0,0,0,0.0)),
color-stop(1.0, rgba(0,0,0,0.5))
);
}
#banner-wrapper
{
overflow: hidden;
}
#feature-wrapper
{
overflow: hidden;
padding: 3em 0em;
background: #5f6b8b url(images/shadow02.png) no-repeat center top;
box-shadow: 0px 10px 5px rgba(0,0,0,.3), 0px -1px 25px rgba(0,0,0,.3);
color: #dfe2e8;
}
#main-wrapper
{
overflow: hidden;
padding: 3em 0em 4em 0em;
background: #f3f3f3 url(images/bg03.jpg) repeat;
box-shadow: 0px 10px 5px rgba(0,0,0,.3), 0px -1px 25px rgba(0,0,0,.3);
}
#footer-wrapper
{
}
#copyright-wrapper
{
background: url(images/gradient.svg);
background:
-moz-linear-gradient(
center bottom,
rgba(0,0,0,0) 5%,
rgba(0,0,0,0.5) 70%
);
background: -webkit-gradient(
linear,
left bottom,
left top,
color-stop(0.0, rgba(0,0,0,0.0)),
color-stop(0.70, rgba(0,0,0,0.5))
);
}
/*********************************************************************************/
/* Feature */
/*********************************************************************************/
#feature-content
{
}
#feature-content h2
{
height: 3.50em;
margin: 0 0 1em 0;
padding: 0 0 0 3.50em;
background: url(images/arrow01.png) no-repeat 0.75em 50%;
border-bottom: 1px solid #949db3;
letter-spacing: -0.02em;
font-size: 1.50em;
color: #FFFFFF;
}
#feature-content span
{
display: inline-block;
height: 3.50em;
padding: 0 0 0 1em;
border-left: 1px solid #949db3;
line-height: 3.5em;
}
/*********************************************************************************/
/* Banner */
/*********************************************************************************/
#banner
{
overflow: hidden;
}
#banner h2
{
display: inline-block;
font-weight: 700;
color: #FFFFFF;
}
#banner .subtitle
{
font-weight: 300;
color: #ababab;
}
/*********************************************************************************/
/* Content */
/*********************************************************************************/
#content
{
}
#content article
{
}
#content .image-left
{
margin-left: 0;
}
/*********************************************************************************/
/* Sidebar */
/*********************************************************************************/
#sidebar
{
}
/*********************************************************************************/
/* Two Column */
/*********************************************************************************/
#two-column
{
}
#two-column .tbox
{
}
#two-column .tbox .image-full
{
padding-bottom: 2em;
}
/*
Registration/Login Form by html-form-guide.com
You can customize all the aspects of the form in this style sheet
*/
#fg_membersite fieldset
{
width: 230px;
padding:20px;
border:1px solid #ccc;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
-khtml-border-radius: 10px;
border-radius: 10px;
}
</code></pre> | 15,089,826 | 4 | 2 | null | 2013-02-26 12:49:24.623 UTC | null | 2013-02-26 13:14:40 UTC | null | null | null | null | 1,249,957 | null | 1 | 9 | html|css | 58,583 | <p>To center a div with <code>margin: 0 auto;</code> like suggested the div must contain a valid width.</p>
<p>If you add </p>
<pre><code>#register{
//...
width: 300px;
margin: 0 auto;
}
</code></pre>
<p>This will center your div in the center horizontally. You can also use <code>text-align: center</code> in the parent with <code>display: inline-block</code> in the form div. Such as:</p>
<pre><code>#fg_membersite{
text-align:center;
}
#register{
display:inline-block;
}
</code></pre>
<p>If you want to center it also in the vertical i suggest you use <code>display:table</code> (on the aprent div) and <code>display:table-cell</code> (in a wrapper div) and <code>vertical-align:middle</code> options , or maybe a <code>position:absolute</code> with negative margins, it's your choice.</p>
<p>Cheers.</p> |
15,177,705 | Can I insert matplotlib graphs into Excel programmatically? | <p>I am saving matplotlib files as .tiff images. I'd like to be able to then open an excel file and paste the image there.</p>
<p>openpyxl doesnot seem to support image embedding. xlwt does but only bmp. </p>
<p>ALternatively if i can programmatically convert tiff to bmp, that might help also. </p>
<p>Ideas on either are welcome. </p>
<p>Similar to </p>
<p><a href="https://stackoverflow.com/questions/15106844/embed-multiple-jpeg-images-into-excel-programmatically">Embed multiple jpeg images into EXCEL programmatically?</a></p>
<p>However converting from tiff to bmp is acceptable as my volume of graphs is small (approximately 10 per file).</p> | 15,177,991 | 3 | 0 | null | 2013-03-02 18:08:44.033 UTC | 6 | 2020-06-18 20:09:49.647 UTC | 2017-05-23 12:26:25.58 UTC | null | -1 | null | 1,419,123 | null | 1 | 16 | python|excel|matplotlib | 40,753 | <p>Here is what I found from two different links on the web, that worked perfectly for me. Matplotlib allows saving png files which is what I make use of here:</p>
<pre><code>from PIL import Image
file_in = "image.png"
img = Image.open(file_in)
file_out = 'test1.bmp'
print len(img.split()) # test
if len(img.split()) == 4:
# prevent IOError: cannot write mode RGBA as BMP
r, g, b, a = img.split()
img = Image.merge("RGB", (r, g, b))
img.save(file_out)
else:
img.save(file_out)
from xlwt import Workbook
w = Workbook()
ws = w.add_sheet('Image')
ws.insert_bitmap(file_out, 0, 0)
w.save('images.xls')
</code></pre>
<p>The image part of the code is from Ene Urans response here <a href="http://www.daniweb.com/software-development/python/threads/253957/converting-an-image-file-png-to-a-bitmap-file" rel="noreferrer">http://www.daniweb.com/software-development/python/threads/253957/converting-an-image-file-png-to-a-bitmap-file</a>.</p>
<p>The xlwt is simply form the documentation of xlwt I found at <a href="http://www.simplistix.co.uk/presentations/python-excel.pdf" rel="noreferrer">http://www.simplistix.co.uk/presentations/python-excel.pdf</a>.</p> |
15,232,600 | Laravel stylesheets and javascript don't load for non-base routes | <p>Okay--I know this is a really elementary issue, but I can't figure it out. <em>This is a question regarding Laravel.</em></p>
<p>Basically, I have my stylesheets embedded in my default layout view. I'm currently just using regular css to link them, such as:</p>
<pre><code><link rel="stylesheet" href="css/app.css" />
</code></pre>
<p>It works great when I am at a single level route such as <strong>/about</strong>, but stops working when I go deeper, such as <strong>/about/me</strong>.</p>
<p>If I look at Chrome's developer console I see some of the following errors (only for the deeper routes):</p>
<pre><code>Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://example.dev/about/css/app.css".
</code></pre>
<p>So clearly it is now looking for the css inside the "about" folder--which of course isn't a folder at all.</p>
<p>I just want it to look in the same place for the assets regardless of the route.</p> | 16,565,640 | 19 | 1 | null | 2013-03-05 19:36:47.177 UTC | 34 | 2020-03-21 20:23:14.86 UTC | null | null | null | null | 1,809,762 | null | 1 | 104 | php|laravel|laravel-blade | 212,158 | <p>For Laravel 4 & 5:</p>
<pre><code><link rel="stylesheet" href="{{ URL::asset('assets/css/bootstrap.min.css') }}">
</code></pre>
<p><strong><a href="https://laravel.com/api/5.7/Illuminate/Contracts/Routing/UrlGenerator.html#method_asset" rel="noreferrer"><code>URL::asset</code></a></strong> will link to your <strong><code>project/public/</code></strong> folder, so chuck your scripts in there.
<hr>
<sup><strong>Note:</strong> For this, you need to use the "<a href="https://laravel.com/docs/master/blade" rel="noreferrer">Blade templating engine</a>". Blade files use the <em><code>.blade.php</code></em> extension.</sup></p> |
38,405,260 | difference between c99 and c11 | <p>I am learning c, presently. <a href="https://rads.stackoverflow.com/amzn/click/com/0393979504" rel="noreferrer" rel="nofollow noreferrer">The book</a> I read is C99 based. I want to update my knowledge to C11 after finishing this book, or change resource if there is a major difference. Thus, what I ask is for is an explanation or resource to update my knowledge. I only found <a href="https://stackoverflow.com/questions/8631228/latest-changes-in-c11">this source</a>. Nevertheless, it does not seem to encompass the information I need or not concise. </p>
<p>Thanks in advance.
P.S: I want to learn C11 since I think it is the prevalent standard now. If not, please inform me.</p> | 38,405,331 | 2 | 3 | null | 2016-07-15 21:27:02.49 UTC | 14 | 2019-08-25 14:53:16.273 UTC | 2017-05-23 12:34:14.767 UTC | null | -1 | null | 6,595,960 | null | 1 | 41 | c|c99|c11 | 43,169 | <p>Good overviews of C11 standard: </p>
<ul>
<li><a href="https://en.wikipedia.org/wiki/C11_(C_standard_revision)" rel="noreferrer">https://en.wikipedia.org/wiki/C11_(C_standard_revision)</a> </li>
<li><a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf</a> </li>
<li><a href="https://smartbear.com/blog/test-and-monitor/c11-a-new-c-standard-aiming-at-safer-programming/" rel="noreferrer">https://smartbear.com/blog/test-and-monitor/c11-a-new-c-standard-aiming-at-safer-programming/</a></li>
</ul>
<p>The standard includes several changes to the C99 language and library specifications, such as:</p>
<ul>
<li>Alignment specification (<code>_Alignas</code> specifier, <code>_Alignof</code> operator, <code>aligned_alloc</code> function, <code><stdalign.h></code> header file)</li>
<li>The <code>_Noreturn</code> function specifier and the <code><stdnoreturn.h></code> header file</li>
<li><p>Type-generic expressions using the <code>_Generic</code> keyword. For example, the following macro <code>cbrt(x)</code> translates to <code>cbrtl(x)</code>, <code>cbrt(x)</code> or <code>cbrtf(x)</code> depending on the type of <code>x</code>:</p>
<pre><code>#define cbrt(x) _Generic((x), long double: cbrtl, \
default: cbrt, \
float: cbrtf)(x)
</code></pre></li>
<li><p>Multi-threading support (<code>_Thread_local</code> storage-class specifier, <code><threads.h></code> header including thread creation/management functions, mutex, condition variable and thread-specific storage functionality, as well as the <code>_Atomic</code> type qualifier and <code><stdatomic.h></code> for uninterruptible object access).</p></li>
<li>Improved Unicode support based on the C Unicode Technical Report ISO/IEC TR 19769:2004 (<code>char16_t</code> and <code>char32_t</code> types for storing <code>UTF-16/UTF-32</code> encoded data, including conversion functions in <code><uchar.h></code> and the corresponding u and U string literal prefixes, as well as the u8 prefix for <code>UTF-8</code> encoded literals).</li>
<li>Removal of the <code>gets</code> function, deprecated in the previous C language standard revision, ISO/IEC 9899:1999/Cor.3:2007(E), in favor of a new safe alternative, <code>gets_s</code>.</li>
<li>Bounds-checking interfaces (Annex K).</li>
<li>Analyzability features (Annex L).</li>
<li>More macros for querying the characteristics of floating point types, concerning subnormal floating point numbers and the number of decimal digits the type is able to store.</li>
<li>Anonymous structures and unions, useful when unions and structures are nested, e.g. in <code>struct T { int tag; union { float x; int n; }; };</code>.</li>
<li>Static assertions, which are evaluated during translation at a later phase than <code>#if</code> and <code>#error</code>, when types are understood by the translator.</li>
<li>An exclusive create-and-open mode (<code>"…x"</code> suffix) for <code>open</code>. This behaves like <code>O_CREAT|O_EXCL</code> in <code>POSIX</code>, which is commonly used for lock files.</li>
<li>The <code>quick_exit</code> function as a third way to terminate a program, intended to do at least minimal deinitialization if termination with <code>exit</code> fails.</li>
<li>Macros for the construction of complex values (partly because <code>real + imaginary*I</code> might not yield the expected value if <code>imaginary</code> is infinite or <code>NaN</code>).</li>
</ul> |
48,178,884 | Min-max normalisation of a NumPy array | <p>I have the following numpy array:</p>
<pre><code>foo = np.array([[0.0, 10.0], [0.13216, 12.11837], [0.25379, 42.05027], [0.30874, 13.11784]])
</code></pre>
<p>which yields:</p>
<pre><code>[[ 0. 10. ]
[ 0.13216 12.11837]
[ 0.25379 42.05027]
[ 0.30874 13.11784]]
</code></pre>
<p>How can I normalize the Y component of this array. So it gives me something like:</p>
<pre><code>[[ 0. 0. ]
[ 0.13216 0.06 ]
[ 0.25379 1 ]
[ 0.30874 0.097]]
</code></pre> | 48,178,963 | 4 | 4 | null | 2018-01-10 01:02:35.557 UTC | 10 | 2019-05-04 22:28:47.113 UTC | 2018-05-30 07:14:31.94 UTC | null | 4,909,087 | null | 513,449 | null | 1 | 17 | python|arrays|numpy | 73,289 | <p>Referring to this Cross Validated Link, <a href="https://stats.stackexchange.com/questions/70801/how-to-normalize-data-to-0-1-range">How to normalize data to 0-1 range?</a>, it looks like you can perform min-max normalisation on the last column of <code>foo</code>. </p>
<pre><code>v = foo[:, 1] # foo[:, -1] for the last column
foo[:, 1] = (v - v.min()) / (v.max() - v.min())
</code></pre>
<p></p>
<pre><code>foo
array([[ 0. , 0. ],
[ 0.13216 , 0.06609523],
[ 0.25379 , 1. ],
[ 0.30874 , 0.09727968]])
</code></pre>
<hr>
<p>Another option for performing normalisation (as suggested by OP) is using <code>sklearn.preprocessing.normalize</code>, which yields slightly different results - </p>
<pre><code>from sklearn.preprocessing import normalize
foo[:, [-1]] = normalize(foo[:, -1, None], norm='max', axis=0)
</code></pre>
<p></p>
<pre><code>foo
array([[ 0. , 0.2378106 ],
[ 0.13216 , 0.28818769],
[ 0.25379 , 1. ],
[ 0.30874 , 0.31195614]])
</code></pre> |
9,016,572 | Unable to Connect to Local SQL Server with Windows Authentication using SSMS | <p>I'm trying to login to my local SQL Server 2005 installed on Windows7 using SSMS using Windows authentication.</p>
<p>I tried using various server names like <code>.</code>, <code>localhost</code>, <code>.\SQL</code>, <code>ANANTH-PC</code> etc.</p>
<p>I get this error when I try <code>.</code> or <code>localhost</code></p>
<p><img src="https://i.stack.imgur.com/QsNXu.png" alt="enter image description here" /></p>
<p>And I get this error when I try <code>.\SQL</code></p>
<p>.<img src="https://i.stack.imgur.com/g96Tv.png" alt="enter image description here" /></p>
<p>I had gone for default instance and Windows authentication when I installed SQL Server.</p>
<p>I've checked the service in the SQL Server Configuration manager and find that <code>MSSQLSERVER</code> is running.</p>
<p>How can I find the server name that I should enter to login to SQL Server? Any help ?</p>
<p>Error is loged as</p>
<pre><code>2012-01-26 15:07:16.02 Logon Login failed for user 'Ananth-PC\Ananth'. [CLIENT: <local machine>]
2012-01-26 15:08:51.06 Logon Error: 18456, Severity: 14, State: 11.
</code></pre> | 9,017,465 | 5 | 6 | null | 2012-01-26 10:14:05.647 UTC | 2 | 2022-09-02 09:06:14.117 UTC | 2022-09-02 09:06:14.117 UTC | null | 8,172,439 | null | 277,087 | null | 1 | 7 | sql-server|database|sql-server-2005|ssms|windows-authentication | 39,691 | <p>That should help you find reason.
Click: "Show technical details" and look at State number.</p>
<p><a href="http://blogs.msdn.com/b/sql_protocols/archive/2006/02/21/536201.aspx" rel="nofollow">http://blogs.msdn.com/b/sql_protocols/archive/2006/02/21/536201.aspx</a></p> |
9,532,608 | Is returning with `std::move` sensible in the case of multiple return statements? | <p>I'm aware that it's normally not a good idea to return with <code>std::move</code>, i.e.</p>
<pre><code>bigObject foo() { bigObject result; /*...*/ return std::move(result); }
</code></pre>
<p>instead of simply</p>
<pre><code>bigObject foo() { bigObject result; /*...*/ return result; }
</code></pre>
<p>because it gets in the way of return value optimization. But what in the case of a function with multiple different returns, particularly something like</p>
<pre><code>class bar {
bigObject fixed_ret;
bool use_fixed_ret;
void prepare_object(bigObject&);
public:
bigObject foo() {
if(use_fixed_ret)
return fixed_ret;
else{
bigObject result;
prepare_object(result);
return result;
}
}
};
</code></pre>
<p>I think normal return value optimization is impossible in such a function, so would it be a good idea to put in</p>
<pre><code> return std::move(result);
</code></pre>
<p>here, or should I rather do (IMO uglier, but that's debatable)</p>
<pre><code> bigObject foo() {
bigObject result;
if(use_fixed_ret)
result = fixed_ret;
else{
prepare_object(result);
}
return result;
}
</code></pre> | 9,532,647 | 1 | 6 | null | 2012-03-02 11:35:17.103 UTC | 9 | 2012-11-16 00:34:36.107 UTC | null | null | null | null | 745,903 | null | 1 | 24 | c++|c++11|move-semantics|return-value-optimization | 7,634 | <p>For local variables, there's no need to <code>std::move</code> them in the <code>return</code> statement most of the time<sup>†</sup>, since the language actually demands that this happens automatically:</p>
<p><code>§12.8 [class.copy] p32</code></p>
<blockquote>
<p>When the criteria for elision of a copy operation are met or would be met save for the fact that the source object is a function parameter, <strong>and the object to be copied is designated by an lvalue, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue</strong>. If overload resolution fails, or if the type of the first parameter of the selected constructor is not an rvalue reference to the object’s type (possibly cv-qualified), overload resolution is performed again, considering the object as an lvalue. [ <em>Note:</em> This two-stage overload resolution must be performed regardless of whether copy elision will occur. It determines the constructor to be called if elision is not performed, and the selected constructor must be accessible even if the call is elided. <em>—end note</em> ]</p>
</blockquote>
<hr>
<p>† Copy elision is very restricted in where it can be applied (<code>§12.8/31</code>). One such restriction is that the type of the source object has to be the same as the cv-unqualified return type of the function when dealing with a return-statement. It's also not applicable for subobjects of local variables that are about to go out of scope.</p> |
8,689,054 | git pull origin master does not update origin/master? | <p>According to the documentation, <strong>git pull</strong> performs a <strong>git fetch</strong> then a git merge, however in that case performing <strong>git pull origin master</strong> should perform a <strong>git fetch origin master</strong> right? However, it does not appear to be doing so. Here is an example.</p>
<p>Supposed my remote origin master (on GitHub in my case) has the following history:</p>
<pre><code>commit 1111111 : my first commit
commit 2222222 : a commit from someone else
</code></pre>
<p>and I only have my first commit locally as doing following shows</p>
<pre><code>git checkout master
git log --pretty=format:'%h' -n 1
1111111
git checkout origin/master
git log --pretty=format:'%h' -n 1
1111111
</code></pre>
<p>From here I do my pull and look at the results as follows:</p>
<pre><code>git checkout master
git pull origin master
git log --pretty=format:'%h' -n 1
2222222
git checkout origin/master
git log --pretty=format:'%h' -n 1
1111111
</code></pre>
<p>As can be seen, the pull did in fact update my master branch with the new commit(s) from the remote origin, but my local origin/master is still where it was. Forcing me to do the following</p>
<pre><code>git fetch origin master
git checkout origin/master
git log --pretty=format:'%h' -n 1
2222222
</code></pre>
<p>Is this correct behavior for git pull or might I have something miss configured? I looked through the git pull man page and didn't see anything that suggested this but I may have missed it.</p> | 8,690,791 | 4 | 4 | null | 2011-12-31 15:58:23.893 UTC | 9 | 2021-09-28 16:50:06.527 UTC | 2012-01-02 19:44:19.837 UTC | null | 229,642 | null | 229,642 | null | 1 | 38 | git|github|git-pull|git-fetch | 51,305 | <p>It's a bit weird, but if you use <code>git pull [remote] <refspec></code> it actually doesn't update the remote refs. It sort of makes sense if you think about it a certain way: since you're specifying a specific ref to fetch, it doesn't have to look up anything about your remote branches, so it doesn't inherently know what remote branch it should update. It of course could figure it out, and I wouldn't be surprised if it gets fixed eventually, but that's the existing behavior. (There may be messages on the mailing list about it - I don't know.)</p>
<p>You can easily work around it, though. If you use <code>git pull origin/master</code>, since you're specifying what to fetch via a remote branch, it should update that remote branch. And if you're on your master branch anyway (or any other branch tracking origin/master), you can just do <code>git pull</code> and let it fill in the defaults, and it will update remote branches.</p>
<p>This is documented in the <code>git-pull</code> man page, most concisely under EXAMPLES but also elsewhere. The relevant part:</p>
<blockquote>
<p>Merge into the current branch the remote branch next:</p>
<pre><code>$ git pull origin next
</code></pre>
<p>This leaves a copy of next temporarily in FETCH_HEAD, but does not update any remote-tracking branches. Using remote-tracking branches, the same can be done by invoking fetch and merge:</p>
<pre><code>$ git fetch origin
$ git merge origin/next
</code></pre>
</blockquote> |
5,217,350 | Reschedule timer in android | <p>How can I reschedule a timer. I have tried to cancel the timer/timertask and and schedule it again using a method. But its showing an exception error:</p>
<pre>
Exception errorjava.lang.IllegalStateException: TimerTask is scheduled already
</pre>
<p>Code I have used it :</p>
<pre>
private Timer timer = new Timer("alertTimer",true);
public void reScheduleTimer(int duration) {
timer.cancel();
timer.schedule(timerTask, 1000L, duration * 1000L);
}
</pre> | 5,217,475 | 4 | 3 | null | 2011-03-07 08:18:44.73 UTC | 9 | 2015-12-08 11:37:20.597 UTC | 2011-03-07 08:28:58.827 UTC | null | 395,959 | null | 395,959 | null | 1 | 35 | android|timer|scheduling | 25,776 | <p>If you see the documentation on Timer.cancel() you'll see this:</p>
<p>"Cancels the Timer and all scheduled tasks. If there is a currently running task it is not affected. No more tasks may be scheduled on this Timer. Subsequent calls do nothing."</p>
<p>You'll need to initialize a new Timer when you are rescheduling:</p>
<p>EDIT:</p>
<pre><code>public void reScheduleTimer(int duration) {
timer = new Timer("alertTimer",true);
timerTask = new MyTimerTask();
timer.schedule(timerTask, 1000L, duration * 1000L);
}
private class MyTimerTask extends TimerTask {
@Override
public void run() {
// Do stuff
}
}
</code></pre> |
5,262,235 | What makes something iterable in python | <p>What makes something iterable in Python? ie. can loop over it with <code>for</code></p>
<p>Is it possible for me to create an iterable class in Python? If so, how?</p> | 5,262,255 | 4 | 0 | null | 2011-03-10 15:57:45.24 UTC | 17 | 2019-10-07 19:17:25.26 UTC | 2015-07-12 13:10:20.413 UTC | null | 284,795 | null | 636,904 | null | 1 | 50 | python | 37,986 | <p>To make a class iterable, write an <code>__iter__()</code> method that returns an iterator:</p>
<pre><code>class MyList(object):
def __init__(self):
self.list = [42, 3.1415, "Hello World!"]
def __iter__(self):
return iter(self.list)
m = MyList()
for x in m:
print(x)
</code></pre>
<p>prints</p>
<pre><code>42
3.1415
Hello World!
</code></pre>
<p>The example uses a list iterator, but you could also write your own iterator by either making <code>__iter__()</code> a <a href="http://docs.python.org/tutorial/classes.html#generators" rel="noreferrer">generator</a> or by returning an instance of an iterator class that defines a <a href="https://docs.python.org/3/library/stdtypes.html#iterator.__next__" rel="noreferrer"><code>__next__()</code></a> method.</p> |
5,571,861 | Joining two tables using LINQ | <p>I have two tables:</p>
<blockquote>
<p>PlanMaster (PlanName, Product_ID)</p>
</blockquote>
<p>and</p>
<blockquote>
<p>ProductPoints (Entity_ID, Product_ID, Comm1, Comm2)</p>
</blockquote>
<p>Now I am storing Entity_ID into a Session which is stored into an 'int':</p>
<pre><code>int getEntity = Int16.Parse(Session["EntitySelected"].ToString());
</code></pre>
<p>I want to show in my LINQ query all of the items from above tables which has </p>
<blockquote>
<p>Entity_ID = getEntity</p>
</blockquote>
<p>Here is my LINQ query:</p>
<pre><code>var td = from s in cv.Entity_Product_Points join r in dt.PlanMasters on s.Product_ID equals r.Product_ID
where s.Entity_ID = getEntity
select s;
</code></pre>
<p>Now its giving me an error which says: </p>
<blockquote>
<p>Cannot implicitly convert type 'int?' to 'bool'</p>
</blockquote>
<p>What is going wrong here? Thank you for your comments in advance!</p> | 5,571,882 | 6 | 0 | null | 2011-04-06 19:25:59.253 UTC | 1 | 2017-04-01 20:11:26.22 UTC | 2011-04-06 19:27:37.777 UTC | null | 119,549 | null | 529,995 | null | 1 | 7 | c#|asp.net|linq|linq-to-sql | 69,431 | <p>Try changing it to</p>
<pre><code> where s.Entity_ID == getEntity
</code></pre> |
4,853,011 | How to sign an android apk file | <p>I am trying to sign my apk file. I can't figure out how to do it. I can't find good in-depth directions. I have very little programing experience, so any help would be appreciated.</p> | 4,853,025 | 6 | 3 | null | 2011-01-31 16:01:09.037 UTC | 35 | 2018-10-16 11:33:52.003 UTC | 2011-12-23 14:59:10.243 UTC | null | 952,925 | null | 595,137 | null | 1 | 117 | android|apk|signing | 201,704 | <p>The manual is clear enough. Please specify what part you get stuck with after you work through it, I'd suggest:</p>
<p><a href="https://developer.android.com/studio/publish/app-signing.html" rel="noreferrer">https://developer.android.com/studio/publish/app-signing.html</a></p>
<p>Okay, a small overview without reference or eclipse around, so leave some space for errors, but it works like this</p>
<ul>
<li>Open your project in eclipse</li>
<li>Press right-mouse - > tools (android tools?) - > export signed application (apk?)</li>
<li>Go through the wizard:</li>
<li>Make a new key-store. remember that password</li>
<li>Sign your app</li>
<li>Save it etc.</li>
</ul>
<p>Also, from the link:</p>
<blockquote>
<p>Compile and sign with Eclipse ADT</p>
<p>If you are using Eclipse with the ADT
plugin, you can use the Export Wizard
to export a signed .apk (and even
create a new keystore, if necessary).
The Export Wizard performs all the
interaction with the Keytool and
Jarsigner for you, which allows you to
sign the package using a GUI instead
of performing the manual procedures to
compile, sign, and align, as discussed
above. Once the wizard has compiled
and signed your package, it will also
perform package alignment with
zip align. Because the Export Wizard
uses both Keytool and Jarsigner, you
should ensure that they are accessible
on your computer, as described above
in the Basic Setup for Signing.</p>
<p>To create a signed and aligned .apk in
Eclipse:</p>
<ol>
<li>Select the project in the Package Explorer and select File >
Export.</li>
<li><p>Open the Android folder, select Export Android Application, and click
Next.</p>
<p>The Export Android Application wizard now starts, which will guide
you through the process of signing
your application, including steps for
selecting the private key with which
to sign the .apk (or creating a new
keystore and private key).</p></li>
<li>Complete the Export Wizard and your application will be compiled,
signed, aligned, and ready for
distribution.</li>
</ol>
</blockquote> |
5,203,535 | Practical uses of git reset --soft? | <p>I have been working with git for just over a month. Indeed I have used reset for the first time only yesterday, but the soft reset still doesn't make much sense to me.</p>
<p>I understand I can use the soft reset to edit a commit without altering the index or the working directory, as I would with <code>git commit --amend</code>. </p>
<p>Are these two commands really the same (<code>reset --soft</code> vs <code>commit --amend</code>)? Any reason to use one or the other in practical terms? And more importantly, are there any other uses for <code>reset --soft</code> apart from amending a commit?</p> | 5,203,843 | 12 | 0 | null | 2011-03-05 11:31:44.363 UTC | 66 | 2022-02-09 16:34:32.983 UTC | 2012-07-30 21:08:13.503 UTC | null | 1,051,522 | null | 377,917 | null | 1 | 182 | git | 330,372 | <p><code>git reset</code> is all about moving <code>HEAD</code>, <a href="https://stackoverflow.com/a/54934887/6309">and generally the branch <em>ref</em></a>.<br>
Question: what about the working tree and index?<br>
When employed with <code>--soft</code>, <strong>moves <code>HEAD</code>, most often updating the branch ref, and only the <code>HEAD</code></strong>.<br>
This differ from <code>commit --amend</code> as:</p>
<ul>
<li>it doesn't create a new commit.</li>
<li>it can actually move HEAD to any commit (as <code>commit --amend</code> is only about <em>not</em> moving HEAD, while allowing to redo the current commit)</li>
</ul>
<hr>
<p>Just found this example of combining:</p>
<ul>
<li>a classic merge</li>
<li>a subtree merge</li>
</ul>
<p>all into one (octopus, since there is more than two branches merged) commit merge.</p>
<p><a href="http://blog.caurea.org/" rel="noreferrer">Tomas "wereHamster" Carnecky</a> explains in his <a href="http://blog.caurea.org/2009/11/19/subtree-octopus-merge.html" rel="noreferrer">"Subtree Octopus merge" article</a>:</p>
<blockquote>
<ul>
<li>The subtree merge strategy can be used if you want to merge one project into a subdirectory of another project, and the subsequently keep the subproject up to date. It is an alternative to git submodules. </li>
<li>The octopus merge strategy can be used to merge three or more branches. The normal strategy can merge only two branches and if you try to merge more than that, git automatically falls back to the octopus strategy. </li>
</ul>
<p>The problem is that you can choose only one strategy. But I wanted to combine the two in order to get a clean history in which the whole repository is atomically updated to a new version.</p>
<p>I have a superproject, let's call it <code>projectA</code>, and a subproject, <code>projectB</code>, that I merged into a subdirectory of <code>projectA</code>. </p>
</blockquote>
<p>(that's the subtree merge part)</p>
<blockquote>
<p>I'm also maintaining a few local commits.<br>
<code>ProjectA</code> is regularly updated, <code>projectB</code> has a new version every couple days or weeks and usually depends on a particular version of <code>projectA</code>. </p>
<p>When I decide to update both projects, I don't simply pull from <code>projectA</code> and <code>projectB</code> <strong>as that would create two commits for what should be an atomic update of the whole project</strong>.<br>
Instead, <strong>I create a single merge commit which combines <code>projectA</code>, <code>projectB</code> and my local commits</strong>.<br>
The tricky part here is that this is an octopus merge (three heads), <strong>but <code>projectB</code> needs to be merged with the subtree strategy</strong>. So this is what I do:</p>
</blockquote>
<pre><code># Merge projectA with the default strategy:
git merge projectA/master
# Merge projectB with the subtree strategy:
git merge -s subtree projectB/master
</code></pre>
<p>Here the author used a <code>reset --hard</code>, and then <code>read-tree</code> to restore what the first two merges had done to the working tree and index, but that is where <strong><code>reset --soft</code></strong> can help:<br>
<strong>How to I redo those two merges</strong>, which have worked, i.e. my working tree and index are fine, but without having to record those two commits?</p>
<pre><code># Move the HEAD, and just the HEAD, two commits back!
git reset --soft HEAD@{2}
</code></pre>
<p>Now, we can resume Tomas's solution:</p>
<pre><code># Pretend that we just did an octopus merge with three heads:
echo $(git rev-parse projectA/master) > .git/MERGE_HEAD
echo $(git rev-parse projectB/master) >> .git/MERGE_HEAD
# And finally do the commit:
git commit
</code></pre>
<hr>
<p>So, each time:</p>
<ul>
<li>you are satisfied with what you end up with (in term of working tree and index)</li>
<li>you are <em>not</em> satisfied with all the commits that took you to get there:</li>
</ul>
<p><code>git reset --soft</code> is the answer.</p> |
5,097,456 | Throw away local commits in Git | <p>Due to some bad cherry-picking, my local Git repository is currently five commits ahead of the origin, and not in a good state. I want to get rid of all these commits and start over again.</p>
<p>Obviously, deleting my working directory and re-cloning would do it, but downloading everything from GitHub again seems like overkill, and not a good use of my time.</p>
<p>Maybe <code>git revert</code> is what I need, but I don't want to end up <em>10</em> commits ahead of the origin (or even six), even if it does get the code itself back to the right state. I just want to pretend the last half-hour never happened.</p>
<p>Is there a simple command that will do this? It seems like an obvious use case, but I'm not finding any examples of it.</p>
<hr>
<p>Note that this question is specifically about <em>commits</em>, <em>not</em> about:</p>
<ul>
<li>untracked files</li>
<li>unstaged changes</li>
<li>staged, but uncommitted changes</li>
</ul> | 5,097,495 | 25 | 1 | null | 2011-02-23 21:33:55.633 UTC | 437 | 2022-09-12 09:28:23.107 UTC | 2019-02-01 21:35:15.643 UTC | null | 63,550 | null | 27,358 | null | 1 | 2,072 | git | 1,564,943 | <p>If your excess commits are only visible to you, you can just do
<code>git reset --hard origin/<branch_name></code>
to move back to where the origin is. This will reset the state of the repository to the previous commit, and it will discard all local changes.</p>
<p>Doing a <code>git revert</code> makes <em>new</em> commits to remove <em>old</em> commits in a way that keeps everyone's history sane.</p> |
41,567,895 | Will scikit-learn utilize GPU? | <p>Reading implementation of scikit-learn in TensorFlow: <a href="http://learningtensorflow.com/lesson6/" rel="noreferrer">http://learningtensorflow.com/lesson6/</a> and scikit-learn: <a href="http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html" rel="noreferrer">http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html</a> I'm struggling to decide which implementation to use.</p>
<p>scikit-learn is installed as part of the tensorflow docker container so can use either implementation.</p>
<p>Reason to use scikit-learn :</p>
<blockquote>
<p>scikit-learn contains less boilerplate than the tensorflow
implementation.</p>
</blockquote>
<p>Reason to use tensorflow :</p>
<blockquote>
<p>If running on Nvidia GPU the algorithm will be run against in parallel
, I'm not sure if scikit-learn will utilize all available GPUs?</p>
</blockquote>
<p>Reading <a href="https://www.quora.com/What-are-the-main-differences-between-TensorFlow-and-SciKit-Learn" rel="noreferrer">https://www.quora.com/What-are-the-main-differences-between-TensorFlow-and-SciKit-Learn</a></p>
<blockquote>
<p>TensorFlow is more low-level; basically, the Lego bricks that help
you to implement machine learning algorithms whereas scikit-learn
offers you off-the-shelf algorithms, e.g., algorithms for
classification such as SVMs, Random Forests, Logistic Regression, and
many, many more. TensorFlow shines if you want to implement
deep learning algorithms, since it allows you to take advantage of
GPUs for more efficient training.</p>
</blockquote>
<p>This statement re-enforces my assertion that "scikit-learn contains less boilerplate than the tensorflow implementation" but also suggests scikit-learn will not utilize all available GPUs?</p> | 41,568,439 | 3 | 4 | null | 2017-01-10 11:37:23.563 UTC | 22 | 2022-02-16 10:10:43.303 UTC | 2021-09-23 10:23:45.06 UTC | null | 10,972,216 | null | 470,184 | null | 1 | 107 | python|tensorflow|scikit-learn|k-means|neuraxle | 138,685 | <p>Tensorflow only uses GPU if it is built against Cuda and CuDNN. By default it does not use GPU, especially if it is running inside Docker, unless you use <a href="https://github.com/NVIDIA/nvidia-docker" rel="noreferrer">nvidia-docker</a> and an image with a built-in support.</p>
<p>Scikit-learn is not intended to be used as a deep-learning framework and it does not provide any GPU support.</p>
<blockquote>
<p><strong>Why is there no support for deep or reinforcement learning / Will there be support for deep or reinforcement learning in scikit-learn?</strong></p>
<p>Deep learning and reinforcement learning both require a rich
vocabulary to define an architecture, with deep learning additionally
requiring GPUs for efficient computing. However, neither of these fit
within the design constraints of scikit-learn; as a result, deep
learning and reinforcement learning are currently out of scope for
what scikit-learn seeks to achieve.</p>
</blockquote>
<p>Extracted from <a href="http://scikit-learn.org/stable/faq.html#why-is-there-no-support-for-deep-or-reinforcement-learning-will-there-be-support-for-deep-or-reinforcement-learning-in-scikit-learn" rel="noreferrer">http://scikit-learn.org/stable/faq.html#why-is-there-no-support-for-deep-or-reinforcement-learning-will-there-be-support-for-deep-or-reinforcement-learning-in-scikit-learn</a></p>
<blockquote>
<p><strong>Will you add GPU support in scikit-learn?</strong></p>
<p>No, or at least not in the near future. The main reason is that GPU
support will introduce many software dependencies and introduce
platform specific issues. scikit-learn is designed to be easy to
install on a wide variety of platforms. Outside of neural networks,
GPUs don’t play a large role in machine learning today, and much
larger gains in speed can often be achieved by a careful choice of
algorithms.</p>
</blockquote>
<p>Extracted from <a href="http://scikit-learn.org/stable/faq.html#will-you-add-gpu-support" rel="noreferrer">http://scikit-learn.org/stable/faq.html#will-you-add-gpu-support</a></p> |
12,181,428 | ASP.NET MVC 4 EF5 with MySQL | <p>So I've just picked up VS2012 and I want to start an ASP.NET MVC 4 app with EF5.</p>
<p>My host does not have MSSQL so I have to use MySQL.</p>
<p>How do I tell my app that it should use MySQL? (I either want to use the devart MySQL connector or the one from mysql.com)</p> | 13,272,547 | 3 | 2 | null | 2012-08-29 15:29:25.943 UTC | 18 | 2017-05-19 07:06:14.303 UTC | 2012-08-29 16:05:04.45 UTC | null | 13,302 | null | 721,768 | null | 1 | 16 | mysql|asp.net-mvc|entity-framework | 30,913 | <p>You need to setup your config with a connection string, DbProviderFactory and a custom DatabaseInitializer for MySql Connector 6.5.4. I have detailed the <a href="http://www.nsilverbullet.net/2012/11/07/6-steps-to-get-entity-framework-5-working-with-mysql-5-5/" rel="nofollow noreferrer">full step for getting EF5 and MySql to play, including code for the initializers on my blog</a>. If you require ASP.Net membership provider solution it been asked before: <a href="https://stackoverflow.com/questions/2038993/asp-net-membership-role-providers-for-mysql/13247593#13247593">ASP.NET Membership/Role providers for MySQL?</a> I will post the solution here also for a complete EF5 MySql solution.</p>
<p>The MySql connector does not currently support EF 5 migration and ASP.NET only supports SimpleMembership (MVC4 default) on MS SQL not MySql. The solution below is for Code First.</p>
<p>The steps are:</p>
<ol>
<li>Grab EF 5 from NuGet</li>
<li>Grab MySql.Data and MySql.Data.Entity from NuGet (6.5.4) or MySql (6.6.4)</li>
<li>Configure a MySql Data Provider</li>
<li>Configure a MySql Connection String</li>
<li>Create a Custom MySql Database Initializer</li>
<li>Configure the Custom MySql Database Initializer</li>
<li>Configure ASP.NET membership if you require it</li>
</ol>
<h2>DbProvider</h2>
<pre class="lang-xml prettyprint-override"><code><system.data>
<DbProviderFactories>
<remove invariant="MySql.Data.MySqlClient"/>
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient"
description=".Net Framework Data Provider for MySQL"
type="MySql.Data.MySqlClient.MySqlClientFactory,MySql.Data" />
</DbProviderFactories>
</system.data>
</code></pre>
<h2>Connection String</h2>
<pre class="lang-xml prettyprint-override"><code><connectionStrings>
<add name="ConnectionStringName"
connectionString="Datasource=hostname;Database=schema_name;uid=username;pwd=Pa$$w0rd;"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</code></pre>
<h2>Database Initializer</h2>
<p>If you are using MySql connector from NuGet (6.5.4) then a custom initializer is required. Code available at <a href="http://brice-lambson.blogspot.se/2012/05/using-entity-framework-code-first-with.html" rel="nofollow noreferrer">http://brice-lambson.blogspot.se/2012/05/using-entity-framework-code-first-with.html</a>
or at <a href="http://www.nsilverbullet.net/2012/11/07/6-steps-to-get-entity-framework-5-working-with-mysql-5-5/" rel="nofollow noreferrer">http://www.nsilverbullet.net/2012/11/07/6-steps-to-get-entity-framework-5-working-with-mysql-5-5/</a></p>
<p>Then add this to configuration</p>
<pre class="lang-xml prettyprint-override"><code><configSections>
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,
EntityFramework, Version=5.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089" />
</configSections>
<entityFramework>
<contexts>
<context type="Namespace.YourContextName, AssemblyName">
<databaseInitializer
type="Namespace.YourChosenInitializer, AssemblyName">
</databaseInitializer>
</context>
</contexts>
<defaultConnectionFactory
type="MySql.Data.MySqlClient.MySqlClientFactory,MySql.Data" />
</entityFramework>
</code></pre>
<h2>ASP.NET Membership</h2>
<pre class="lang-xml prettyprint-override"><code><membership defaultProvider="MySqlMembershipProvider">
<providers>
<clear />
<add name="MySqlMembershipProvider"
type="MySql.Web.Security.MySQLMembershipProvider,
MySql.Web, Version=6.5.4.0, PublicKeyToken=c5687fc88969c44d"
autogenerateschema="true"
connectionStringName="*NAME_OF_YOUR_CONN_STRING*"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""
applicationName="/" />
</providers>
</membership>
</code></pre>
<p>Get the AccountController and Views working:</p>
<ol>
<li>Delete the MVC 4 AccountController, AccountModels, Account view folder and _LoginPartial shared view</li>
<li>Create a new MVC 3 web application</li>
<li>Copy the MVC 3 AccountController, AccountModels, Account view folder and _LogOnPartial shared view into your MVC 4 application</li>
<li>Replace <code>@Html.Partial(“_LoginPartial”)</code> in the shared _Layout view with <code>@Html.Partial(“_LogOnPartial”)</code></li>
</ol> |
12,402,594 | How to plot overlaying time series in R? | <p>I would like to compare the values of two different variables in time.</p>
<p>For example, having two datasets:</p>
<p>dataset1(Date, value)
and
dataset2(Date, value)</p>
<p>In order to plot just first, we can execute the following:</p>
<pre><code>x.Date <- as.Date(dataset1$Date)
x <- zoo(dataset1$Value, x.Date)
plot(x)
</code></pre>
<p>To the same window I would like to add (dataset2$value, dataset2$Date), and by chance set the different color.</p>
<p>the values dataset1$Date and dataset2$Date are not neccessary the same (some days might overlap and some not), for example dataset1$Date might contain (dec01, dec02, dec03, dec05) and dataset2$Date (dec02, dec03, dec06).</p>
<p>Does anyone know how to plot two (or several) time plots in the same window?</p> | 12,402,893 | 5 | 0 | null | 2012-09-13 08:47:17.467 UTC | 10 | 2020-03-09 07:14:50.513 UTC | 2017-08-23 10:10:53.35 UTC | null | 3,848,765 | null | 22,996 | null | 1 | 24 | r|plot | 68,441 | <p>There are several options. Here are three options working with <code>zoo</code> objects.</p>
<pre><code>set.seed(1)
xz = zoo(ts(rnorm(20), frequency = 4, start = c(1959, 2)))
yz = zoo(ts(rnorm(20), frequency = 4, start = c(1959, 2)))
# Basic approach
plot(xz)
lines(yz, col = "red")
# Panels
plot.zoo(cbind(xz, yz))
# Overplotted
plot.zoo(cbind(xz, yz),
plot.type = "single",
col = c("red", "blue"))
</code></pre>
<hr>
<p>If you are plotting regular <code>ts</code> objects, you can also explore <code>ts.plot</code>:</p>
<pre><code>set.seed(1)
x = ts(rnorm(20), frequency = 4, start = c(1959, 2))
y = ts(rnorm(20), frequency = 4, start = c(1959, 2))
ts.plot(x, y, gpars = list(col = c("black", "red")))
</code></pre> |
12,314,849 | Html.DisplayFor not posting values to controller in ASP.NET MVC 3 | <p>I am using ASP.NET MVC 3 with Razor, below is a sample from my view code.</p>
<p>The user should be able to edit all their details, except the "EmailAddress" field. For that field only I have used <code>Html.DisplayFor(m => m.EmailAddress)</code>.</p>
<p>But when this form gets posted, all the model properties are filled except the <code>EmailAddress</code>. </p>
<p>How do I get the email back in the model when posting? Should I have used some helper other than <code>DisplayFor</code>?</p>
<pre><code>@using (Html.BeginForm()) {
@Html.ValidationSummary(true, "Account update was unsuccessful. Please correct any errors and try again.")
<div>
<fieldset>
<legend>Update Account Information</legend>
<div class="editor-label">
@Html.LabelFor(m => m.EmailAddress)
</div>
<div class="editor-field">
@Html.DisplayFor(m => m.EmailAddress)
@*@Html.ValidationMessageFor(m => m.EmailAddress)*@
</div>
<div class="editor-label">
@Html.LabelFor(m => m.FirstName)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.FirstName)
@Html.ValidationMessageFor(m => m.FirstName)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.LastName)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.LastName)
@Html.ValidationMessageFor(m => m.LastName)
</div>
<p>
<input type="submit" value="Update" />
</p>
</fieldset>
</div>
}
</code></pre>
<p>Please advise me on this.</p> | 12,314,879 | 1 | 0 | null | 2012-09-07 08:55:26.47 UTC | 5 | 2016-12-29 16:57:53.55 UTC | 2016-12-29 16:57:53.55 UTC | null | 2,263,584 | null | 1,182,982 | null | 1 | 39 | asp.net-mvc|asp.net-mvc-3|razor | 21,647 | <p>you'll need to add a</p>
<pre><code>@Html.HiddenFor(m => m.EmailAddress)
</code></pre>
<p><code>DisplayFor</code> won't send anything in POST, it won't create an input...</p>
<p>By the way, an</p>
<p><code>@Html.HiddenFor(m => m.Id) // or anything which is the model key</code></p>
<p>would be usefull</p> |
12,162,634 | Where do I define the domain to be used by url_for() in Flask? | <p>When I call <code>url_for('index')</code> it will generate <code>'/'</code> but there are times where I'd like it to generate <code>'domain.tld/'</code> instead. I can't find in the documentation where I would specify this. Do I just need to do <code>'domain.tld/%s' % url_for('index')</code>?</p> | 12,162,726 | 1 | 0 | null | 2012-08-28 15:30:28.517 UTC | 12 | 2012-08-28 15:35:51.2 UTC | null | null | null | null | 1,389,451 | null | 1 | 82 | python|flask|url-for | 41,860 | <p><a href="http://flask.pocoo.org/docs/api/#flask.url_for" rel="noreferrer"><code>url_for</code></a> takes an <code>_external</code> keyword argument that will return an absolute (rather than relative) URL. I believe you will need to set a <code>SERVER_NAME</code> config key with your root domain to make it work correctly.</p> |
44,283,540 | iter() not working with datetime.now() | <p>A simple snippet in Python 3.6.1:</p>
<pre><code>import datetime
j = iter(datetime.datetime.now, None)
next(j)
</code></pre>
<p>returns:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
</code></pre>
<p>instead of printing out the classic <code>now()</code> behavior with each <code>next()</code>.</p>
<p>I've seen similar code working in Python 3.3, am I missing something or has something changed in version 3.6.1?</p> | 44,284,085 | 2 | 3 | null | 2017-05-31 11:27:01.957 UTC | 5 | 2017-06-20 21:25:35.093 UTC | 2017-05-31 13:27:50.04 UTC | null | 5,393,381 | null | 1,063,607 | null | 1 | 44 | python|datetime|python-3.6|iterable | 1,621 | <p>This is definitely a bug introduced in Python 3.6.0b1. The <code>iter()</code> implementation recently switched to using <code>_PyObject_FastCall()</code> (an optimisation, see <a href="http://bugs.python.org/issue27128" rel="nofollow noreferrer">issue 27128</a>), and it must be this call that is breaking this.</p>
<p>The same issue arrises with other C <code>classmethod</code> methods backed by Argument Clinic parsing:</p>
<pre><code>>>> from asyncio import Task
>>> Task.all_tasks()
set()
>>> next(iter(Task.all_tasks, None))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
</code></pre>
<p>If you need a work-around, wrap the callable in a <code>functools.partial()</code> object:</p>
<pre><code>from functools import partial
j = iter(partial(datetime.datetime.now), None)
</code></pre>
<p>I filed <a href="http://bugs.python.org/issue30524" rel="nofollow noreferrer">issue 30524 -- <em>iter(classmethod, sentinel) broken for Argument Clinic class methods?</em></a> with the Python project. The fix for this has landed and is part of 3.6.2rc1.</p> |
3,637,419 | Multiple Database Config in Django 1.2 | <p>This is hopefully an easy question.</p>
<p>I'm having some trouble understanding the documentation for the new multiple database feature in Django 1.2. Primarily, I cant seem to find an example of how you actually USE the second database in one of your models.</p>
<p>When I define a new class in my models.py how do I specify which database I intend on connecting to?</p>
<p>My settings.py contains something similar to -</p>
<pre><code>DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'modules',
'USER': 'xxx',
'PASSWORD': 'xxx',
},
'asterisk': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'users',
'USER': 'xxxx',
'PASSWORD': 'xxxx',
}
}
</code></pre>
<p>Edit: I was reading the documentation on routers like a dummy. If anyone else is struggling with this just make sure you read it 2 or 3 times before giving up!</p> | 3,638,091 | 3 | 0 | null | 2010-09-03 15:50:17.437 UTC | 9 | 2011-04-23 21:16:02.563 UTC | 2010-09-03 17:15:22.1 UTC | null | 241,642 | null | 241,642 | null | 1 | 20 | python|django|django-models | 3,453 | <p>Yeah, it is a little bit complicated.</p>
<p>There are a number of ways you could implement it. Basically, you need some way of indicating which models are associated with which database. </p>
<h1>First option</h1>
<p>Here's the code that I use; hope it helps.</p>
<pre><code>from django.db import connections
class DBRouter(object):
"""A router to control all database operations on models in
the contrib.auth application"""
def db_for_read(self, model, **hints):
m = model.__module__.split('.')
try:
d = m[-1]
if d in connections:
return d
except IndexError:
pass
return None
def db_for_write(self, model, **hints):
m = model.__module__.split('.')
try:
d = m[-1]
if d in connections:
return d
except IndexError:
pass
return None
def allow_syncdb(self, db, model):
"Make sure syncdb doesn't run on anything but default"
if model._meta.app_label == 'myapp':
return False
elif db == 'default':
return True
return None
</code></pre>
<p>The way this works is I create a file with the name of the database to use that holds my models. In your case, you'd create a separate <code>models</code>-style file called <code>asterisk.py</code> that was in the same folder as the models for your app.</p>
<p>In your <code>models.py</code> file, you'd add</p>
<pre><code>from asterisk import *
</code></pre>
<p>Then when you actually request a record from that model, it works something like this:</p>
<ol>
<li><code>records = MyModel.object.all()</code></li>
<li>module for <code>MyModel</code> is <code>myapp.asterisk</code> </li>
<li>there's a connection called "asterisk" so use
it instead of "default"</li>
</ol>
<h1>Second Option</h1>
<p>If you want to have per-model control of database choice, something like this would work:</p>
<pre><code>from django.db import connections
class DBRouter(object):
"""A router to control all database operations on models in
the contrib.auth application"""
def db_for_read(self, model, **hints):
if hasattr(model,'connection_name'):
return model.connection_name
return None
def db_for_write(self, model, **hints):
if hasattr(model,'connection_name'):
return model.connection_name
return None
def allow_syncdb(self, db, model):
if hasattr(model,'connection_name'):
return model.connection_name
return None
</code></pre>
<p>Then for each model:</p>
<pre><code>class MyModel(models.Model):
connection_name="asterisk"
#etc...
</code></pre>
<p>Note that I have not tested this second option.</p> |
3,724,110 | Practical example of Polymorphism | <p>Can anyone please give me a real life, practical example of Polymorphism? My professor tells me the same old story I have heard always about the <code>+</code> operator. <code>a+b = c</code> and <code>2+2 = 4</code>, so this is polymorphism. I really can't associate myself with such a definition, since I have read and re-read this in many books.</p>
<p>What I need is a real world example with code, something that I can truly associate with. </p>
<p>For example, here is a small example, just in case you want to extend it.</p>
<pre><code>>>> class Person(object):
def __init__(self, name):
self.name = name
>>> class Student(Person):
def __init__(self, name, age):
super(Student, self).__init__(name)
self.age = age
</code></pre> | 3,724,160 | 3 | 2 | null | 2010-09-16 06:03:31.547 UTC | 43 | 2022-08-28 09:04:46.8 UTC | null | null | null | null | 449,154 | null | 1 | 60 | python|oop|polymorphism | 85,427 | <p>Check the Wikipedia example: it is very helpful at a high level:</p>
<pre><code>class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
def talk(self): # Abstract method, defined by convention only
raise NotImplementedError("Subclass must implement abstract method")
class Cat(Animal):
def talk(self):
return 'Meow!'
class Dog(Animal):
def talk(self):
return 'Woof! Woof!'
animals = [Cat('Missy'),
Cat('Mr. Mistoffelees'),
Dog('Lassie')]
for animal in animals:
print animal.name + ': ' + animal.talk()
# prints the following:
#
# Missy: Meow!
# Mr. Mistoffelees: Meow!
# Lassie: Woof! Woof!
</code></pre>
<p>Notice the following: all animals "talk", but they talk differently. The "talk" behaviour is thus polymorphic in the sense that it is <em>realized differently depending on the animal</em>. So, the abstract "animal" concept does not actually "talk", but specific animals (like dogs and cats) have a concrete implementation of the action "talk".</p>
<p>Similarly, the "add" operation is defined in many mathematical entities, but in particular cases you "add" according to specific rules: 1+1 = 2, but (1+2i)+(2-9i)=(3-7i).</p>
<p>Polymorphic behaviour allows you to specify common methods in an "abstract" level, and implement them in particular instances.</p>
<p>For your example:</p>
<pre><code>class Person(object):
def pay_bill(self):
raise NotImplementedError
class Millionare(Person):
def pay_bill(self):
print "Here you go! Keep the change!"
class GradStudent(Person):
def pay_bill(self):
print "Can I owe you ten bucks or do the dishes?"
</code></pre>
<p>You see, millionares and grad students are both persons. But when it comes to paying a bill, their specific "pay the bill" action is different.</p> |
20,818,881 | use video as background for div | <p>I would like to use a video as background in CSS3. I know that there is no background-video property, but is it possible to do this behavior. Using a fullsize video-tag doesn't give the wanted result, cause there is content that need to be displayed over the video.</p>
<p>It need to be non JS. If it is not possible then I need to do changes on my serverside an give as result also a screenshot of the video.</p>
<p>I need the video to replace the colored boxes:</p>
<p><img src="https://i.stack.imgur.com/GOpUc.png" alt="Boxes"></p>
<p>The colored boxes are atm just, CSS boxes.</p> | 20,820,618 | 3 | 5 | null | 2013-12-28 20:10:37.507 UTC | 14 | 2021-04-26 13:46:06.073 UTC | 2014-01-02 20:59:13.683 UTC | null | 1,126,393 | null | 1,126,393 | null | 1 | 37 | html|css|html5-video | 155,241 | <p>Why not fix a <code><video></code> and use <code>z-index:-1</code> to put it behind all other elements?</p>
<pre><code>html, body { width:100%; height:100%; margin:0; padding:0; }
<div style="position: fixed; top: 0; width: 100%; height: 100%; z-index: -1;">
<video id="video" style="width:100%; height:100%">
....
</video>
</div>
<div class='content'>
....
</code></pre>
<p><a href="http://jsfiddle.net/M2DCk/" rel="noreferrer"><strong>Demo</strong></a></p>
<p>If you want it within a container you have to add a container element and a little more CSS</p>
<pre><code>/* HTML */
<div class='vidContain'>
<div class='vid'>
<video> ... </video>
</div>
<div class='content'> ... The rest of your content ... </div>
</div>
/* CSS */
.vidContain {
width:300px; height:200px;
position:relative;
display:inline-block;
margin:10px;
}
.vid {
position: absolute;
top: 0; left:0;
width: 100%; height: 100%;
z-index: -1;
}
.content {
position:absolute;
top:0; left:0;
background: black;
color:white;
}
</code></pre>
<p><a href="http://jsfiddle.net/M2DCk/2/" rel="noreferrer"><strong>Demo</strong></a></p> |
22,095,487 | Why is package-info.java useful? | <p>When I run CheckStyle over my Java project it says <code>Missing package-info.java file.</code> for some classes, but not all of them. I can't really figure out why this message appears only sometimes. Furthermore my project runs perfectly fine without the package-info.java.</p>
<p>What does the package-info.java do? Do I really need it for my Java projects?</p> | 22,095,639 | 5 | 4 | null | 2014-02-28 12:38:47.797 UTC | 31 | 2019-02-13 10:16:53.603 UTC | 2014-02-28 12:44:28.017 UTC | null | 327,038 | null | 3,164,889 | null | 1 | 136 | java|maven|checkstyle | 81,729 | <p>It is used to generate javadocs for a package.</p>
<pre><code>/**
* Domain classes used to produce .....
* <p>
* These classes contain the ......
* </p>
*
* @since 1.0
* @author somebody
* @version 1.0
*/
package com.domain;
</code></pre>
<p>Will generate package info for <code>com.domain</code> package:</p>
<p>Example result: <a href="https://docs.oracle.com/javase/7/docs/api/java/awt/package-summary.html" rel="noreferrer">https://docs.oracle.com/javase/7/docs/api/java/awt/package-summary.html</a></p> |
11,025,491 | Google Apps Script - Send Email based on date in cell | <p>I've looked around and have bits and pieces but can't put the puzzle together. I'm attempting to create a script that will run on a trigger configured to run daily. The trigger will be setup under Resources option in the editor.</p>
<p>Basically I'm looking for the script to capture a range of cells, identify a due date, which will be populated in a column, match it to the current date. If it matches then send a email. I've started with the send a email from spreadsheet tutorial at Google. I've added in a if statement to check for the date but I'm losing it on the comparsion to dataRange. Anyone might help correct these or point me to in direction to research.</p>
<p>The script appears to run but nothing happens, which I believe is because "if (currentTime == dataRange)" The dataRange is not matching correctly??</p>
<p>Here is the code:</p>
<pre><code>function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 50; // Number of rows to process
// Fetch the range of cells
var dataRange = sheet.getRange(startRow, 1, numRows, 2)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
//Get todays date
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
//Test column for date due & match to current date
if ( currentTime == dataRange) {
for (i in data) {
var row = data[i];
var emailAddress = row[0]; // First column
var message = row[1]; // Second column
var subject = "Task Item Due";
MailApp.sendEmail(emailAddress, subject, message);
}
}
}
</code></pre>
<p>I'm updating the suggestion provided by Srik and providing his suggestion in the below code. I've attempted to post this a couple time so I'm not sure why its not making past peer review?</p>
<pre><code> function sendEmail() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 50; // Number of rows to process
var dataRange = sheet.getRange(startRow, 1, numRows, 50);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
//Browser.msgBox(data)
for (i in data) {
var row = data[i];
var date = new Date();
var sheetDate = new Date(row[1]);
if (date.getDate() == sheetDate.getDate() && date.getMonth() == sheetDate.getMonth() && date.getFullYear() == sheetDate.getFullYear());
{
var emailAddress = row[0]; // First column
var message = row[2]; // Second column
var subject = "Sending emails from a Spreadsheet";
MailApp.sendEmail(emailAddress, subject, message);
// Browser.msgBox(emailAddress)
}
}
}
</code></pre>
<p>The code appears to run but I'm getting the following error w/in the script editor. "Failed to send email: no recipient (line 23)". But it still sends emails. It should compare the dates and only send the email if the date matches. Its sending an email for every row. I've shared out the spreadsheet to see the code and how the spreadsheet is setup. <a href="https://docs.google.com/spreadsheet/ccc?key=0AiB8MImvI1UMdGx0WTRsUmVHSjl1dVNPTkxtWlNmcGc" rel="noreferrer">Shared Spreadsheet</a></p>
<p>UPDATED CODE W/ SERGE HELP on the logger and Utilities.formatDate.. Thanks!!</p>
<pre><code>function sendEmail() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = sheet.getLastRow()-1; // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, sheet.getLastColumn());
// Fetch values for each row in the Range.
var data = dataRange.getValues();
//Logger.log(data)
for (i in data) {
var row = data[i];
var date = new Date();
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
//Logger.log(date);
var sheetDate = new Date(row[2]);
//Logger.log(sheetDate);
var Sdate = Utilities.formatDate(date,'GMT+0200','yyyy:MM:dd')
var SsheetDate = Utilities.formatDate(sheetDate,'GMT+0200', 'yyyy:MM:dd')
Logger.log(Sdate+' =? '+SsheetDate)
if (Sdate == SsheetDate){
var emailAddress = row[0]; // First column
var message = row[1]; // Second column
var subject = "Your assigned task is due today." +message;
MailApp.sendEmail(emailAddress, subject, message);
//Logger.log('SENT :'+emailAddress+' '+subject+' '+message)
}
}
}
</code></pre> | 11,067,517 | 3 | 0 | null | 2012-06-14 01:16:22.76 UTC | 11 | 2013-02-04 19:29:01.583 UTC | 2012-06-17 02:36:10.763 UTC | null | 1,455,081 | null | 1,455,081 | null | 1 | 5 | javascript|google-apps-script|google-sheets | 31,623 | <p>here is a working version of your code, I used Utilities.formatDate to make strings of your dates, so you can choose what you compare (only days, hours ? min ?) </p>
<p>I commented the mail call just for my tests, re-enable it when you need</p>
<pre><code>function sendEmail() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = sheet.getLastRow()-1; // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, sheet.getLastColumn());
// Fetch values for each row in the Range.
var data = dataRange.getValues();
Logger.log(data)
for (i in data) {
var row = data[i];
var date = new Date();
var sheetDate = new Date(row[1]);
Sdate=Utilities.formatDate(date,'GMT+0200','yyyy:MM:dd')
SsheetDate=Utilities.formatDate(sheetDate,'GMT+0200', 'yyyy:MM:dd')
Logger.log(Sdate+' =? '+SsheetDate)
if (Sdate == SsheetDate){
var emailAddress = row[0]; // First column
var message = row[2]; // Second column
var subject = "Sending emails from a Spreadsheet";
// MailApp.sendEmail(emailAddress, subject, message);
Logger.log('SENT :'+emailAddress+' '+subject+' '+message)
}
}
}
</code></pre>
<p>don't forget to look at the logs ;-)</p> |
11,144,783 | How to access an image from the phone's photo gallery? | <p>By any chance, does anyone know how to access the phone's photo gallery?
I am making an application that takes a picture of a plant leaf and
analyzes the image to determine whether or not it is determine. We were hoping that we
could give the user two options of taking the picture of the leaf or using an image of a
leaf that the user has already taken. However, we got the picture taking part, but we do not
know how to access the photo gallery.</p> | 11,144,927 | 2 | 0 | null | 2012-06-21 18:48:00.16 UTC | 10 | 2016-11-09 21:05:12.9 UTC | 2014-09-04 23:34:34.567 UTC | null | 881,229 | null | 1,473,060 | null | 1 | 20 | android|android-gallery | 63,164 | <p>You have to launch the Gallery App using the built-in <code>Intents</code>. After that, on your <code>onActivityResult()</code>, get the path of the selected image and load your image into your <code>ImageView</code></p>
<p>main.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/loadimage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Load Image"
/>
<TextView
android:id="@+id/targeturi"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ImageView
android:id="@+id/targetimage"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
</code></pre>
<p>Your Activity</p>
<pre><code> package com.exercise.AndroidSelectImage;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class AndroidSelectImage extends Activity {
TextView textTargetUri;
ImageView targetImage;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonLoadImage = (Button)findViewById(R.id.loadimage);
textTargetUri = (TextView)findViewById(R.id.targeturi);
targetImage = (ImageView)findViewById(R.id.targetimage);
buttonLoadImage.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
Uri targetUri = data.getData();
textTargetUri.setText(targetUri.toString());
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
targetImage.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
</code></pre>
<p><img src="https://i.stack.imgur.com/mtMBe.png" alt="enter image description here"></p> |
11,188,338 | How to animate a View's translation | <p>At the first click of a button, I want to slide a <code>View</code> along the x-axis (by 200 pixels to the right let's say). And on the second press of the button, I want to slide the <code>View</code> back along the x-axis to its original position.</p>
<p>The <code>View.setTranslationX(float)</code> method <em>jumps</em> the View to the target horizontal locations with calls <code>myView.setTranslationX(200);</code> and <code>myView.setTranslationX(0);</code> respectively. Anyone know how I can <em>slide</em> the <code>View</code> to the target horizontal locations instead?</p>
<blockquote>
<p><strong>Note 1:</strong> A <code>TranslateAnimation</code> is no good since it doesn't actually move
the <code>View</code> but only presents the illusion of it moving.</p>
<p><strong>Note 2:</strong> I didn't realise at the time of posing the question that the <code>setTranslationX(float)</code> and <code>setTranslationY(float)</code> methods were introduced as of API Level 11. If you're targeting Honeycomb (API Level 11) upwards, then Gautam K's answer will suffice. Otherwise, see my answer for a suggested solution.</p>
</blockquote> | 11,309,652 | 3 | 0 | null | 2012-06-25 11:18:08.897 UTC | 6 | 2013-12-26 07:06:44.267 UTC | 2012-07-03 12:53:42.777 UTC | null | 1,071,320 | null | 1,071,320 | null | 1 | 21 | android|android-animation|android-view | 44,044 | <p>This one's had me stumped for a fair few days (getting it to work pre- Ice Cream Sandwich) but I think I've finally got there! (thanks to Gautam K and Mike Israel for the leads) What I did in the end was to extend my <code>View</code> (a <code>FrameLayout</code>) to start the translate right/left animations as required and to listen for the end of the animations in order to relocate my <code>FrameLayout</code> right/left as appropriate, as follows:</p>
<pre><code>public class SlidingFrameLayout extends FrameLayout
{
private final int durationMilliseconds = 1000;
private final int displacementPixels = 200;
private boolean isInOriginalPosition = true;
private boolean isSliding = false;
public SlidingFrameLayout(Context context)
{
super(context);
}
public SlidingFrameLayout(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public SlidingFrameLayout(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
@Override
protected void onAnimationEnd()
{
super.onAnimationEnd();
if (isInOriginalPosition)
offsetLeftAndRight(displacementPixels);
else
offsetLeftAndRight(-displacementPixels);
isSliding = false;
isInOriginalPosition = !isInOriginalPosition;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom)
{
super.onLayout(changed, left, top, right, bottom);
// need this since otherwise this View jumps back to its original position
// ignoring its displacement
// when (re-)doing layout, e.g. when a fragment transaction is committed
if (changed && !isInOriginalPosition)
offsetLeftAndRight(displacementPixels);
}
public void toggleSlide()
{
// check whether frame layout is already sliding
if (isSliding)
return; // ignore request to slide
if (isInOriginalPosition)
startAnimation(new SlideRightAnimation());
else
startAnimation(new SlideLeftAnimation());
isSliding = true;
}
private class SlideRightAnimation extends TranslateAnimation
{
public SlideRightAnimation()
{
super(
Animation.ABSOLUTE, 0,
Animation.ABSOLUTE, displacementPixels,
Animation.ABSOLUTE, 0,
Animation.ABSOLUTE, 0);
setDuration(durationMilliseconds);
setFillAfter(false);
}
}
private class SlideLeftAnimation extends TranslateAnimation
{
public SlideLeftAnimation()
{
super(
Animation.ABSOLUTE, 0,
Animation.ABSOLUTE, -displacementPixels,
Animation.ABSOLUTE, 0,
Animation.ABSOLUTE, 0);
setDuration(durationMilliseconds);
setFillAfter(false);
}
}
}
</code></pre>
<p>And, lastly, to slide the <code>SlidingFrameLayout</code> right/left, all you've got to do is call the <code>SlidingFrameLayout.toggleSlide()</code> method. Of course you can tweak this <code>SlidingFrameLayout</code> for your purposes to slide a greater number of pixels, to slide for longer etc, but this should be sufficient to get you started :)</p> |
11,343,388 | Is there a way to get a list of all classes from a .dex file? | <p>I have a <code>.dex</code> file, call it <code>classes.dex</code>. </p>
<p>Is there a way to "read" the contents of that <code>classes.dex</code> and get a list of all classes in there as full class names, including their package, <code>com.mypackage.mysubpackage.MyClass</code>, for exmaple?</p>
<p>I was thinking about <a href="http://www.jarvana.com/jarvana/view/com/google/android/tools/dx/1.7/dx-1.7-javadoc.jar!/com/android/dx/dex/file/DexFile.html" rel="noreferrer"><code>com.android.dx.dex.file.DexFile</code></a>, but I cannot seem to find a method for retrieving an entire set of classes.</p> | 11,350,724 | 5 | 0 | null | 2012-07-05 11:28:26.373 UTC | 15 | 2020-09-23 16:10:00.65 UTC | null | null | null | null | 904,692 | null | 1 | 52 | java|android|class|dex|dx | 39,939 | <p>You can use the <a href="https://code.google.com/p/smali/source/browse/#git/dexlib/src/main/java/org/jf/dexlib" rel="noreferrer">dexlib2 library</a> as a standalone library (<a href="http://search.maven.org/#artifactdetails%7Corg.smali%7Cdexlib2%7C2.0.3%7Cjar" rel="noreferrer">available in maven</a>), to read the dex file and get a list of classes.</p>
<pre><code>DexFile dexFile = DexFileFactory.loadDexFile("classes.dex", 19 /*api level*/);
for (ClassDef classDef: dexFile.getClasses()) {
System.out.println(classDef.getType());
}
</code></pre>
<p>Note that the class names will be of the form "Ljava/lang/String;", which is how they are stored in the dex file (and in a java class file). To convert, just remove the first and last letter, and replace / with .</p> |
10,896,111 | Sharing constant strings in Java across many classes? | <p>I'd like to have Java constant strings at one place and use them across whole project (many classes). </p>
<p>What is the recommended way of achieveing this? </p> | 10,896,131 | 10 | 6 | null | 2012-06-05 11:01:22.033 UTC | 14 | 2021-07-29 08:26:31.68 UTC | null | null | null | null | 1,202,172 | null | 1 | 63 | java|string | 72,461 | <pre><code>public static final String CONSTANT_STRING="CONSTANT_STRING";
</code></pre>
<p>constants should be:</p>
<ol>
<li>public - so that it can be accessed from anywhere</li>
<li>static - no need to create an instance</li>
<li>final - since its constants shouldnt be allowed to change</li>
<li>As per Java naming convention should be capitalized so that easy to read and stands out in Java documentation.</li>
</ol>
<p>There are instances where interfaces are used just to keep constants, but this is considered a bad practice because interfaces are supposed to <a href="https://docs.oracle.com/javase/tutorial/java/concepts/interface.html" rel="nofollow noreferrer">define the behavior</a> of a type.</p>
<p>A better approach is to keep it in the class where it makes more sense.</p>
<p>for e.g.</p>
<p><code>JFrame</code> has <code>EXIT_ON_CLOSE</code> contant, any class which subclasses <code>JFrame</code> will have access to it and it also makes sense to keep in <code>JFrame</code> and not in <code>JComponent</code> as not all components will have an option to be closed.</p> |
13,152,329 | Finding stored procedures having execute permission | <p>I am using SQL Server 2008 R2. I need to list out all the stored procedures that a database user (MYUSER) has execute permission. </p>
<p>Also, I need to list out which are the stored procedures that the user does NOT have EXECUTE permission - but can read the script of the stored procedure</p>
<p>Is there any SQL statement or helper function for these purpose?</p>
<p>REFERENCE:</p>
<ol>
<li><a href="https://stackoverflow.com/questions/5109581/granting-execute-permission-on-all-stored-procedures-in-a-certain-database">Granting execute permission on all stored procedures in a certain database</a></li>
</ol> | 13,153,460 | 5 | 0 | null | 2012-10-31 06:22:07.393 UTC | 3 | 2020-11-06 19:14:59.51 UTC | 2017-05-23 11:45:26.457 UTC | null | -1 | null | 696,627 | null | 1 | 15 | sql-server|stored-procedures|sql-server-2008-r2 | 50,127 | <p>Use <a href="http://msdn.microsoft.com/en-us/library/ms189802.aspx"><code>HAS_PERMS_BY_NAME</code></a>:</p>
<pre><code>select name,
has_perms_by_name(name, 'OBJECT', 'EXECUTE') as has_execute,
has_perms_by_name(name, 'OBJECT', 'VIEW DEFINITION') as has_view_definition
from sys.procedures
</code></pre> |
13,027,708 | SQL multiple columns in IN clause | <p>If we need to query a table based on some set of values for a given column, we can simply use the IN clause. </p>
<p>But if query need to be performed based on multiple columns, we could not use IN clause(grepped in SO threads.) </p>
<p>From other SO threads, we can circumvent this problem using joins or exists clause etc. But they all work if both main table and search data are in the database. </p>
<pre><code>E.g
User table:
firstName, lastName, City
</code></pre>
<p>Given a list of (firstname, lastName) tuples, I need to get the cities. </p>
<p>I can think of following solutions. </p>
<h1>1</h1>
<p>Construct a select query like, </p>
<pre><code>SELECT city from user where (firstName=x and lastName=y) or (firstName=a and lastName=b) or .....
</code></pre>
<h1>2</h1>
<p>Upload all firstName, lastName values into a staging table and perform a join between 'user' table and the new staging table. </p>
<p>Are there any options for solving this problem and what is the preferred of solving this problem in general?</p> | 13,027,780 | 6 | 6 | null | 2012-10-23 09:46:28.873 UTC | 14 | 2017-02-10 07:23:19.99 UTC | 2012-10-23 11:26:52.247 UTC | null | 1,235,565 | null | 1,677,236 | null | 1 | 43 | sql|oracle | 221,557 | <p>You could do like this:</p>
<pre><code>SELECT city FROM user WHERE (firstName, lastName) IN (('a', 'b'), ('c', 'd'));
</code></pre>
<p><em><strong><a href="http://sqlfiddle.com/#!2/72132/4/0">The sqlfiddle</a></em></strong>.</p> |
12,817,027 | Is there vim plugin for notepad++? | <p>There are a lot of questions and answers about <code>vim</code> and <code>notepad++</code> but it's not definitely clear, what is best way to make <code>notepad++</code> act like a <code>vim</code> (if it is possible at all).</p>
<p><strong>update</strong><br>
It seems than this question needs some additional information of my motivation. I assume myself as a vim beginner. It's quite difficult for me to change my editor at one moment. I think than vim plugin for my current editor can give me easy way to feel more comfort in new environment.</p> | 12,818,855 | 4 | 4 | null | 2012-10-10 10:18:17.563 UTC | 13 | 2016-10-20 00:50:37.3 UTC | 2012-10-10 11:37:33.017 UTC | null | 1,035,174 | null | 1,035,174 | null | 1 | 74 | vim|plugins|notepad++|text-editor | 85,270 | <p>Most of what makes Vim what it is derives from the fact that it's a <em>modal</em> editor. If there's no way to turn NP++ into a modal editor you won't get far. A quick look at <a href="http://sourceforge.net/apps/mediawiki/notepad-plus/index.php?title=Plugin_Central">NP++ plugins page</a> shows no Vi[m] plugin so I'd answer "no".</p>
<p>Whatever, the best way to learn Vim is to use it. I'd suggest you keep using NP++ for serious work and force yourself to use Vim for everything else. Once, if ever, you'll be ready, drop NP++ and use Vim full time.</p> |
30,295,174 | What is the performance of std::bitset? | <p>I recently asked a question on <a href="https://softwareengineering.stackexchange.com/questions/284160/is-there-any-advantage-to-c-style-bit-manipulation-over-stdbitset">Programmers</a> regarding reasons to use manual bit manipulation of primitive types over <code>std::bitset</code>.</p>
<p>From that discussion I have concluded that the main reason is its comparatively poorer performance, although I'm not aware of any measured basis for this opinion. So next question is:</p>
<p><strong>what <em>is</em> the performance hit, if any, likely to be incurred by using <code>std::bitset</code> over bit-manipulation of a primitive?</strong></p>
<p>The question is intentionally broad, because after looking online I haven't been able to find anything, so I'll take what I can get. Basically I'm after a resource that provides some profiling of <code>std::bitset</code> vs 'pre-bitset' alternatives to the same problems on some common machine architecture using GCC, Clang and/or VC++. There is a very comprehensive paper which attempts to answer this question for bit vectors:</p>
<p><a href="http://www.cs.up.ac.za/cs/vpieterse/pub/PieterseEtAl_SAICSIT2010.pdf" rel="noreferrer">http://www.cs.up.ac.za/cs/vpieterse/pub/PieterseEtAl_SAICSIT2010.pdf</a></p>
<p>Unfortunately, it either predates or considered out of scope <code>std::bitset</code>, so it focuses on vectors/dynamic array implementations instead.</p>
<p>I really just want to know whether <code>std::bitset</code> is <em>better</em> than the alternatives for the use cases it is intended to solve. I already know that it is <em>easier</em> and <em>clearer</em> than bit-fiddling on an integer, but is it as <em>fast</em>?</p> | 30,295,642 | 5 | 11 | null | 2015-05-18 04:35:24.017 UTC | 14 | 2020-11-04 18:39:34.98 UTC | 2018-11-09 22:21:19.823 UTC | null | 3,964,927 | null | 1,613,983 | null | 1 | 60 | c++|performance|bitset | 41,165 | <p><strong>Update</strong></p>
<p>It's been ages since I posted this one, but:</p>
<blockquote>
<p>I already know that it is easier and clearer than bit-fiddling on an
integer, but is it as fast?</p>
</blockquote>
<p>If you are using <code>bitset</code> in a way that does actually make it clearer and cleaner than bit-fiddling, like checking for one bit at a time instead of using a bit mask, then inevitably you lose all those benefits that bitwise operations provide, like being able to check to see if 64 bits are set at one time against a mask, or using FFS instructions to quickly determine which bit is set among 64-bits.</p>
<p>I'm not sure that <code>bitset</code> incurs a penalty to use in all ways possible (ex: using its bitwise <code>operator&</code>), but if you use it <em>like</em> a fixed-size boolean array which is pretty much the way I always see people using it, then you generally lose all those benefits described above. We unfortunately can't get that level of expressiveness of just accessing one bit at a time with <code>operator[]</code> and have the optimizer figure out all the bitwise manipulations and FFS and FFZ and so forth going on for us, at least not since the last time I checked (otherwise <code>bitset</code> would be one of my favorite structures).</p>
<p>Now if you are going to use <code>bitset<N> bits</code> interchangeably with like, say, <code>uint64_t bits[N/64]</code> as in accessing both the same way using bitwise operations, it might be on par (haven't checked since this ancient post). But then you lose many of the benefits of using <code>bitset</code> in the first place.</p>
<p><strong><code>for_each</code> method</strong></p>
<p>In the past I got into some misunderstandings, I think, when I proposed a <code>for_each</code> method to iterate through things like <code>vector<bool></code>, <code>deque</code>, and <code>bitset</code>. The point of such a method is to utilize the internal knowledge of the container to iterate through elements more efficiently while invoking a functor, just as some associative containers offer a <code>find</code> method of their own instead of using <code>std::find</code> to do a better than linear-time search.</p>
<p>For example, you can iterate through all set bits of a <code>vector<bool></code> or <code>bitset</code> if you had internal knowledge of these containers by checking for 64 elements at a time using a 64-bit mask when 64 contiguous indices are occupied, and likewise use FFS instructions when that's not the case.</p>
<p>But an iterator design having to do this type of scalar logic in <code>operator++</code> would inevitably have to do something considerably more expensive, just by the nature in which iterators are designed in these peculiar cases. <code>bitset</code> lacks iterators outright and that often makes people wanting to use it to avoid dealing with bitwise logic to use <code>operator[]</code> to check each bit individually in a sequential loop that just wants to find out which bits are set. That too is not nearly as efficient as what a <code>for_each</code> method implementation could do.</p>
<p><strong>Double/Nested Iterators</strong></p>
<p>Another alternative to the <code>for_each</code> container-specific method proposed above would be to use double/nested iterators: that is, an outer iterator which points to a sub-range of a different type of iterator. Client code example:</p>
<pre><code>for (auto outer_it = bitset.nbegin(); outer_it != bitset.nend(); ++outer_it)
{
for (auto inner_it = outer_it->first; inner_it != outer_it->last; ++inner_it)
// do something with *inner_it (bit index)
}
</code></pre>
<p>While not conforming to the flat type of iterator design available now in standard containers, this can allow some very interesting optimizations. As an example, imagine a case like this:</p>
<pre><code>bitset<64> bits = 0x1fbf; // 0b1111110111111;
</code></pre>
<p>In that case, the outer iterator can, with just a few bitwise iterations ((FFZ/or/complement), deduce that the first range of bits to process would be bits [0, 6), at which point we can iterate through that sub-range very cheaply through the inner/nested iterator (it would just increment an integer, making <code>++inner_it</code> equivalent to just <code>++int</code>). Then when we increment the outer iterator, it can then very quickly, and again with a few bitwise instructions, determine that the next range would be [7, 13). After we iterate through that sub-range, we're done. Take this as another example:</p>
<pre><code>bitset<16> bits = 0xffff;
</code></pre>
<p>In such a case, the first and last sub-range would be <code>[0, 16)</code>, and the bitset could determine that with a single bitwise instruction at which point we can iterate through all set bits and then we're done.</p>
<p>This type of nested iterator design would map particularly well to <code>vector<bool></code>, <code>deque</code>, and <code>bitset</code> as well as other data structures people might create like unrolled lists.</p>
<p>I say that in a way that goes beyond just armchair speculation, since I have a set of data structures which resemble the likes of <code>deque</code> which are actually on par with sequential iteration of <code>vector</code> (still noticeably slower for random-access, especially if we're just storing a bunch of primitives and doing trivial processing). However, to achieve the comparable times to <code>vector</code> for sequential iteration, I had to use these types of techniques (<code>for_each</code> method and double/nested iterators) to reduce the amount of processing and branching going on in each iteration. I could not rival the times otherwise using just the flat iterator design and/or <code>operator[]</code>. And I'm certainly not smarter than the standard library implementers but came up with a <code>deque</code>-like container which can be sequentially iterated much faster, and that strongly suggests to me that it's an issue with the standard interface design of iterators in this case which come with some overhead in these peculiar cases that the optimizer cannot optimize away.</p>
<p><strong>Old Answer</strong></p>
<p>I'm one of those who would give you a similar performance answer, but I'll try to give you something a bit more in-depth than <code>"just because"</code>. It is something I came across through actual profiling and timing, not merely distrust and paranoia.</p>
<p>One of the biggest problems with <code>bitset</code> and <code>vector<bool></code> is that their interface design is "too convenient" if you want to use them like an array of booleans. Optimizers are great at obliterating all that structure you establish to provide safety, reduce maintenance cost, make changes less intrusive, etc. They do an especially fine job with selecting instructions and allocating the minimal number of registers to make such code run as fast as the not-so-safe, not-so-easy-to-maintain/change alternatives.</p>
<p>The part that makes the bitset interface "too convenient" at the cost of efficiency is the random-access <code>operator[]</code> as well as the iterator design for <code>vector<bool></code>. When you access one of these at index <code>n</code>, the code has to first figure out which byte the nth bit belongs to, and then the sub-index to the bit within that. That first phase typically involves a division/rshifts against an lvalue along with modulo/bitwise and which is more costly than the actual bit operation you're trying to perform.</p>
<p>The iterator design for <code>vector<bool></code> faces a similar awkward dilemma where it either has to branch into different code every 8+ times you iterate through it or pay that kind of indexing cost described above. If the former is done, it makes the logic asymmetrical across iterations, and iterator designs tend to take a performance hit in those rare cases. To exemplify, if <code>vector</code> had a <code>for_each</code> method of its own, you could iterate through, say, a range of 64 elements at once by just masking the bits against a 64-bit mask for <code>vector<bool></code> if all the bits are set without checking each bit individually. It could even use <a href="https://en.wikipedia.org/wiki/Find_first_set" rel="noreferrer">FFS</a> to figure out the range all at once. An iterator design would tend to inevitably have to do it in a scalar fashion or store more state which has to be redundantly checked every iteration.</p>
<p>For random access, optimizers can't seem to optimize away this indexing overhead to figure out which byte and relative bit to access (perhaps a bit too runtime-dependent) when it's not needed, and you tend to see significant performance gains with that more manual code processing bits sequentially with advanced knowledge of which byte/word/dword/qword it's working on. It's somewhat of an unfair comparison, but the difficulty with <code>std::bitset</code> is that there's no way to make a fair comparison in such cases where the code knows what byte it wants to access in advance, and more often than not, you tend to have this info in advance. It's an apples to orange comparison in the random-access case, but you often only need oranges.</p>
<p>Perhaps that wouldn't be the case if the interface design involved a <code>bitset</code> where <code>operator[]</code> returned a proxy, requiring a two-index access pattern to use. For example, in such a case, you would access bit 8 by writing <code>bitset[0][6] = true; bitset[0][7] = true;</code> with a template parameter to indicate the size of the proxy (64-bits, e.g.). A good optimizer may be able to take such a design and make it rival the manual, old school kind of way of doing the bit manipulation by hand by translating that into: <code>bitset |= 0x60;</code></p>
<p>Another design that might help is if <code>bitsets</code> provided a <code>for_each_bit</code> kind of method, passing a bit proxy to the functor you provide. That might actually be able to rival the manual method.</p>
<p><code>std::deque</code> has a similar interface problem. Its performance shouldn't be <em>that</em> much slower than <code>std::vector</code> for sequential access. Yet unfortunately we access it sequentially using <code>operator[]</code> which is designed for random access or through an iterator, and the internal rep of deques simply don't map very efficiently to an iterator-based design. If deque provided a <code>for_each</code> kind of method of its own, then there it could potentially start to get a lot closer to <code>std::vector's</code> sequential access performance. These are some of the rare cases where that Sequence interface design comes with some efficiency overhead that optimizers often can't obliterate. Often good optimizers can make convenience come free of runtime cost in a production build, but unfortunately not in all cases.</p>
<p><strong>Sorry!</strong></p>
<p>Also sorry, in retrospect I wandered a bit with this post talking about <code>vector<bool></code> and <code>deque</code> in addition to <code>bitset</code>. It's because we had a codebase where the use of these three, and particularly iterating through them or using them with random-access, were often hotspots.</p>
<p><strong>Apples to Oranges</strong></p>
<p>As emphasized in the old answer, comparing straightforward usage of <code>bitset</code> to primitive types with low-level bitwise logic is comparing apples to oranges. It's not like <code>bitset</code> is implemented very inefficiently for what it does. If you genuinely need to access a bunch of bits with a random access pattern which, for some reason or other, needs to check and set just one bit a time, then it might be ideally implemented for such a purpose. But my point is that almost all use cases I've encountered didn't require that, and when it's not required, the old school way involving bitwise operations tends to be significantly more efficient.</p> |
16,862,337 | Lua Semicolon Conventions | <p>I was wondering if there is a general convention for the usage of semicolons in Lua, and if so, where/why should I use them? I come from a programming background, so ending statements with a semicolon seems intuitively correct. However I was concerned as to why they are <code>"optional"</code> when its generally accepted that semicolons end statements in other programming languages. Perhaps there is some benefit?</p>
<p>For example: From the <a href="http://www.lua.org/pil/1.1.html" rel="noreferrer">lua programming guide</a>, these are all acceptable, equivalent, and syntactically accurate:</p>
<pre><code>a = 1
b = a*2
a = 1;
b = a*2;
a = 1 ; b = a*2
a = 1 b = a*2 -- ugly, but valid
</code></pre>
<p>The author also mentions: <code>Usually, I use semicolons only to separate two or more statements written in the same line, but this is just a convention.</code> </p>
<p>Is this generally accepted by the Lua community, or is there another way that is preferred by most? Or is it as simple as my personal preference?</p> | 16,863,076 | 5 | 0 | null | 2013-05-31 17:01:15.353 UTC | 2 | 2020-01-10 10:23:40.547 UTC | 2019-03-24 20:24:02.177 UTC | null | 10,607,772 | null | 1,366,973 | null | 1 | 30 | lua|conventions | 30,899 | <p>Semi-colons in Lua are generally only required when writing multiple statements on a line.</p>
<p>So for example:</p>
<pre><code>local a,b=1,2; print(a+b)
</code></pre>
<p>Alternatively written as:</p>
<pre><code>local a,b=1,2
print(a+b)
</code></pre>
<p>Off the top of my head, I can't remember any other time in Lua where I <em>had</em> to use a semi-colon.</p>
<p>Edit: looking in the lua 5.2 reference I see one other common place where you'd need to use semi-colons to avoid ambiguity - where you have a simple statement followed by a function call or parens to group a compound statement. here is the manual example located <a href="http://www.lua.org/manual/5.2/manual.html#3.3" rel="noreferrer">here</a>:</p>
<pre><code>--[[ Function calls and assignments can start with an open parenthesis. This
possibility leads to an ambiguity in the Lua grammar. Consider the
following fragment: ]]
a = b + c
(print or io.write)('done')
-- The grammar could see it in two ways:
a = b + c(print or io.write)('done')
a = b + c; (print or io.write)('done')
</code></pre> |
25,563,640 | Difference between Semaphore initialized with 1 and 0 | <p>Please tell what is difference Semaphore initialized with 1 and zero. as below:</p>
<pre><code>public static Semaphore semOne = new Semaphore(1);
</code></pre>
<p>and</p>
<pre><code>public static Semaphore semZero = new Semaphore(0);
</code></pre> | 25,563,825 | 3 | 5 | null | 2014-08-29 07:35:42.953 UTC | 8 | 2021-09-09 15:36:41.213 UTC | null | null | null | null | 2,307,097 | null | 1 | 27 | java|java.util.concurrent | 24,614 | <p>The argument to the Semaphore instance is the number of "permits" that are available. It can be any integer, not just 0 or 1. </p>
<p>For <code>semZero</code> all <code>acquire()</code> calls will block and <code>tryAcquire()</code> calls will return false, until you do a <code>release()</code></p>
<p>For <code>semOne</code> the first <code>acquire()</code> calls will succeed and the rest will block until the first one releases. </p>
<p>The class is well documented <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Semaphore.html" rel="noreferrer">here</a>.</p>
<blockquote>
<p>Parameters: permits - the initial number of permits available. This
value may be negative, in which case releases must occur before any
acquires will be granted.</p>
</blockquote> |
4,379,403 | Jquery event handlers return values | <p>Is there any use to return values from <code>.click()</code> and <code>.change()</code> handlers (like <code>return true</code> or <code>return false</code>)?</p> | 4,379,459 | 2 | 2 | null | 2010-12-07 17:03:57.05 UTC | 8 | 2016-01-04 20:02:45.213 UTC | 2010-12-07 17:09:52.68 UTC | null | 427,328 | null | 27,238 | null | 1 | 39 | javascript|jquery | 25,763 | <p><code>return false;</code> will stop the event from bubbling up <em>AND</em> suppress the default action.</p>
<p>In otherwords, returning false is analogous to these two lines</p>
<pre><code>event.stopPropagation();
event.preventDefault();
</code></pre>
<p>For events that bubble and are cancelable, at least.</p> |
41,573,769 | Firebase vs AngularFire | <p>I am working on an <code>Angular App</code>, which is connected with <code>Firebase</code> Real-time database. I am currently using <a href="https://github.com/firebase/angularfire" rel="noreferrer">AngularFire</a> for accessing <code>Firebase</code> database.</p>
<p>After reading <code>Vanilla Firebase</code> and <code>AngularFire</code> documentation, and after implementing some portion of my app, I saw that all the things required from <code>Firebase</code> database can be achieved with the help of Vanilla Firebase, without any help of <code>AngularFire</code>.</p>
<p>Also, <code>AngularFire</code> provides only limited number of resources as compared to <code>Vanilla Firebase</code>. So, why would I want to use <code>AngularFire</code>, instead of <code>Vanilla Firebase</code>, when it has many resources available with it? I cant get my head around this scenario.</p>
<p>What are the benefits of using <code>AngularFire</code> over <code>Vanilla Firebase</code>?</p> | 41,619,533 | 1 | 8 | null | 2017-01-10 16:37:18.983 UTC | 14 | 2019-12-02 04:30:24.293 UTC | 2019-12-02 04:30:24.293 UTC | null | 5,084,000 | null | 5,084,000 | null | 1 | 34 | angularjs|angular|firebase|firebase-realtime-database|angularfire | 12,968 | <h1>Angularfire</h1>
<p>Well, angularfire is sort of a helper library. It's supposed to make your life easier by providing bindings that were created in order to make the integration between angular and firebase more seamless. </p>
<p>A practical example:</p>
<p>Developers normally need to make use of arrays in order to display data. However, firebase does not store any data in array form. Instead, it uses a JSON-like structure. That being said, to make it easier for everyone to wrap their heads around retrieving data from firebase as an array, angularfire gives you $firebaseArray(), which essentially converts the data from a certain location and returns you that same data inside of an array (a read-only pseudo-array).</p>
<p>Note that all of that could be accomplished by just retrieving the data manually with vanilla firebase and then converting the data you got from firebase (as an object) to an array on the client side.</p>
<p>You should use angularfire when it makes sense to you and if it makes your life easier. That is what it is there for. If you can accomplish everything you need by just using vanilla firebase, there's no reason to complicate things. I should also point out that you can use firebase and angularfire at the same time. As cartant mentioned in the comments, it is not an either-or choice, as both play together very well. That means that you can use vanilla firebase for more specific use cases, while utilizing angularfire for other purposes.</p>
<p>All in all, everything that is possible to do with angularfire is also possible with vanilla firebase, although it may require a whole bunch of extra code. In other words, angularfire is built on top of firebase and will not offer you new firebase features. Essentially, it makes using firebase with angular a lot more fun and practical.</p>
<h1>Angularfire2</h1>
<p>Angularfire2 is a totally different story, since it actually integrates RxJS observables and other reactive patterns with firebase, all of which are not available by default in vanilla firebase.</p>
<p>For the most part though, they both serve the same purpose. Angularfire2 is also an abstraction on top of firebase that provides real time bindings which were meant to facilitate the integration between firebase and angular2. Additionally, it gives you the possibility of working with firebase in a reactive way.</p> |
10,212,213 | round number to 2 decimal places | <p>I need to round a number to two decimal places.
Right now the following rounds to the nearest integer I guess</p>
<pre><code>puts [expr {round($total_rate)}]
</code></pre>
<p>If I do something like below it does not work. Is there another way around?</p>
<pre><code>puts [expr {round($total_rate,2)}]
</code></pre> | 10,212,642 | 4 | 1 | null | 2012-04-18 15:02:23.09 UTC | 3 | 2022-07-10 03:01:42.487 UTC | null | null | null | null | 856,753 | null | 1 | 10 | tcl|rounding | 54,819 | <pre><code>expr {double(round(100*$total_rate))/100}
</code></pre>
<p>example</p>
<pre><code>% set total_rate 1.5678
1.5678
% expr {double(round(100*$total_rate))/100}
1.57
% set total_rate 1.4321
1.4321
% expr {double(round(100*$total_rate))/100}
1.43
</code></pre> |
10,242,351 | Display an alert when internet connection not available in android application | <p>In my application data comes from internet and I am trying to create a function that checks if a internet connection is available or not and if it isn't, it gives an alert messege that no internet connection available.
i am using following code. but its not working.</p>
<pre><code>public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
if (isOnline())
{
// my code
}
else
{
Hotgames4meActivity1.this.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
try {
AlertDialog alertDialog = new AlertDialog.Builder(Hotgames4meActivity1.this).create();
alertDialog.setTitle("Info");
alertDialog.setMessage("Internet not available, Cross check your internet connectivity and try again");
//alertDialog.setIcon(R.drawable.alerticon);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.show();
}
catch(Exception e)
{
//Log.d(Constants.TAG, "Show Dialog: "+e.getMessage());
}
}
}
</code></pre> | 10,243,015 | 15 | 5 | null | 2012-04-20 07:57:19.63 UTC | 9 | 2021-12-05 08:26:56.897 UTC | 2016-12-29 05:45:02.827 UTC | null | 2,429,040 | null | 1,244,537 | null | 1 | 15 | android|alert | 84,537 | <pre><code>public void onCreate(Bundle obj) {
super.onCreate(obj)
setContextView(layout);
if (isOnline()) {
//do whatever you want to do
} else {
try {
AlertDialog alertDialog = new AlertDialog.Builder(con).create();
alertDialog.setTitle("Info");
alertDialog.setMessage("Internet not available, Cross check your internet connectivity and try again");
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.show();
} catch (Exception e) {
Log.d(Constants.TAG, "Show Dialog: " + e.getMessage());
}
}
}
</code></pre> |
10,231,206 | Can scipy.stats identify and mask obvious outliers? | <p>With scipy.stats.linregress I am performing a simple linear regression on some sets of highly correlated x,y experimental data, and initially visually inspecting each x,y scatter plot for outliers. More generally (i.e. programmatically) is there a way to identify and mask outliers?</p> | 16,166,069 | 4 | 0 | null | 2012-04-19 15:14:37.12 UTC | 16 | 2017-05-04 14:57:13.383 UTC | null | null | null | null | 857,416 | null | 1 | 24 | python|statistics|scipy|linear-regression | 25,294 | <p>The <code>statsmodels</code> package has what you need. Look at this little code snippet and its output:</p>
<pre><code># Imports #
import statsmodels.api as smapi
import statsmodels.graphics as smgraphics
# Make data #
x = range(30)
y = [y*10 for y in x]
# Add outlier #
x.insert(6,15)
y.insert(6,220)
# Make graph #
regression = smapi.OLS(x, y).fit()
figure = smgraphics.regressionplots.plot_fit(regression, 0)
# Find outliers #
test = regression.outlier_test()
outliers = ((x[i],y[i]) for i,t in enumerate(test) if t[2] < 0.5)
print 'Outliers: ', list(outliers)
</code></pre>
<p><img src="https://i.stack.imgur.com/bo8CC.png" alt="Example figure 1"></p>
<p><code>Outliers: [(15, 220)]</code></p>
<h1>Edit</h1>
<p>With the newer version of <code>statsmodels</code>, things have changed a bit. Here is a new code snippet that shows the same type of outlier detection.</p>
<pre><code># Imports #
from random import random
import statsmodels.api as smapi
from statsmodels.formula.api import ols
import statsmodels.graphics as smgraphics
# Make data #
x = range(30)
y = [y*(10+random())+200 for y in x]
# Add outlier #
x.insert(6,15)
y.insert(6,220)
# Make fit #
regression = ols("data ~ x", data=dict(data=y, x=x)).fit()
# Find outliers #
test = regression.outlier_test()
outliers = ((x[i],y[i]) for i,t in enumerate(test.icol(2)) if t < 0.5)
print 'Outliers: ', list(outliers)
# Figure #
figure = smgraphics.regressionplots.plot_fit(regression, 1)
# Add line #
smgraphics.regressionplots.abline_plot(model_results=regression, ax=figure.axes[0])
</code></pre>
<p><img src="https://i.stack.imgur.com/4iVLo.png" alt="Example figure 2"></p>
<p><code>Outliers: [(15, 220)]</code></p> |
9,728,407 | Trouble converting long list of data.frames (~1 million) to single data.frame using do.call and ldply | <p>I know there are many questions here in SO about ways to convert a list of data.frames to a single data.frame using do.call or ldply, but this questions is about understanding the inner workings of both methods and trying to figure out why I can't get either to work for concatenating a list of almost 1 million df's of the same structure, same field names, etc. into a single data.frame. Each data.frame is of one row and 21 columns.</p>
<p>The data started out as a JSON file, which I converted to lists using fromJSON, then ran another lapply to extract part of the list and converted to data.frame and ended up with a list of data.frames.</p>
<p>I've tried:</p>
<pre><code>df <- do.call("rbind", list)
df <- ldply(list)
</code></pre>
<p>but I've had to kill the process after letting it run up to 3 hours and not getting anything back.</p>
<p>Is there a more efficient method of doing this? How can I troubleshoot what is happening and why is it taking so long?</p>
<p>FYI - I'm using RStudio server on a 72GB quad-core server with RHEL, so I don't think memory is the problem. sessionInfo below:</p>
<pre><code>> sessionInfo()
R version 2.14.1 (2011-12-22)
Platform: x86_64-redhat-linux-gnu (64-bit)
locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
[3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
[5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
[7] LC_PAPER=C LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] multicore_0.1-7 plyr_1.7.1 rjson_0.2.6
loaded via a namespace (and not attached):
[1] tools_2.14.1
>
</code></pre> | 12,290,824 | 4 | 18 | null | 2012-03-15 21:25:02.38 UTC | 12 | 2012-09-06 23:14:23.32 UTC | 2012-09-06 12:40:22.193 UTC | null | 403,310 | null | 142,068 | null | 1 | 25 | performance|r|plyr|data.table|do.call | 4,228 | <p>Given that you are looking for performance, it appears that a <code>data.table</code> solution should be suggested.</p>
<p>There is a function <code>rbindlist</code> which is the <code>same</code> but much faster than <code>do.call(rbind, list)</code></p>
<pre><code>library(data.table)
X <- replicate(50000, data.table(a=rnorm(5), b=1:5), simplify=FALSE)
system.time(rbindlist.data.table <- rbindlist(X))
## user system elapsed
## 0.00 0.01 0.02
</code></pre>
<p>It is also <strong>very</strong> fast for a list of <code>data.frame</code></p>
<pre><code>Xdf <- replicate(50000, data.frame(a=rnorm(5), b=1:5), simplify=FALSE)
system.time(rbindlist.data.frame <- rbindlist(Xdf))
## user system elapsed
## 0.03 0.00 0.03
</code></pre>
<p>For comparison</p>
<pre><code>system.time(docall <- do.call(rbind, Xdf))
## user system elapsed
## 50.72 9.89 60.88
</code></pre>
<p>And some proper benchmarking</p>
<pre><code>library(rbenchmark)
benchmark(rbindlist.data.table = rbindlist(X),
rbindlist.data.frame = rbindlist(Xdf),
docall = do.call(rbind, Xdf),
replications = 5)
## test replications elapsed relative user.self sys.self
## 3 docall 5 276.61 3073.444445 264.08 11.4
## 2 rbindlist.data.frame 5 0.11 1.222222 0.11 0.0
## 1 rbindlist.data.table 5 0.09 1.000000 0.09 0.0
</code></pre>
<h1>and against @JoshuaUlrich's solutions</h1>
<pre><code>benchmark(use.rbl.dt = rbl.dt(X),
use.rbl.ju = rbl.ju (Xdf),
use.rbindlist =rbindlist(X) ,
replications = 5)
## test replications elapsed relative user.self
## 3 use.rbindlist 5 0.10 1.0 0.09
## 1 use.rbl.dt 5 0.10 1.0 0.09
## 2 use.rbl.ju 5 0.33 3.3 0.31
</code></pre>
<p>I'm not sure you really need to use <code>as.data.frame</code>, because a <code>data.table</code> inherits class <code>data.frame</code></p> |
9,650,808 | Android javax.annotation.processing Package missing | <p>I would like to do some annotation processing based on the example in the following link: <a href="http://www.zdnetasia.com/writing-and-processing-custom-annotations-part-3-39362483.htm" rel="noreferrer">http://www.zdnetasia.com/writing-and-processing-custom-annotations-part-3-39362483.htm</a>.</p>
<p>However, I would like to implement this in my Android project, and it seems I cannot use the package with the android platform. Do I need to add an external jar or is there something I'm missing?</p>
<p>Thanks.</p> | 9,650,862 | 8 | 0 | null | 2012-03-10 22:39:35.73 UTC | 7 | 2021-07-02 13:03:36.09 UTC | null | null | null | null | 677,393 | null | 1 | 29 | android|annotations|annotation-processing | 29,171 | <p>The <code>javax.annotation.processing</code> package is not included in Android, but the Android VM team describes how to include extra <code>javax</code> packages <a href="http://web.archive.org/web/20120414114022/http://code.google.com/p/dalvik/wiki/JavaxPackages" rel="noreferrer">here</a> - it might be applicable to your question.</p> |
9,898,627 | What is the difference between Pan and Swipe in iOS? | <p>Sounds simple .. <strong>Hold the Trackpad, move the finger, release</strong> .. But somehow swipe is not being triggered (pan is triggered instead)</p>
<pre><code>UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc]
initWithTarget:v action:@selector(handleSwipe:)];
swipeGesture.direction= UISwipeGestureRecognizerDirectionUp;
[v addGestureRecognizer:swipeGesture];
</code></pre>
<p>Pan is recognized by the above sequence instead.</p>
<pre><code>UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc]
initWithTarget:v action:@selector(handlePan:)];
[v addGestureRecognizer: panGesture];
</code></pre>
<p>If pan is commented, swipe is recognized by the same gesture .. With this, 2 questions:</p>
<ul>
<li><strong>What is the difference then between a pan and a swipe?</strong></li>
<li><strong>How can one simulate a swipe on iPhone simulator?</strong></li>
</ul> | 9,899,299 | 3 | 1 | null | 2012-03-27 22:27:52.66 UTC | 29 | 2017-08-14 11:25:12.23 UTC | 2012-03-27 22:33:21.86 UTC | null | 359,862 | null | 359,862 | null | 1 | 135 | ios|gesture-recognition|gestures | 67,661 | <p>By definition, a swipe gesture is necessarily also a pan gesture -- both involve translational movement of touch points. The difference is in the recognizer semantics: a pan recognizer looks for the beginning of translational movement and continues to report movement in any direction over time, while a swipe recognizer makes an instantaneous decision as to whether the user's touches moved linearly in the required direction. </p>
<p>By default, no two recognizers will recognize the same gesture, so there's a conflict between pan and swipe. Most likely, your pan recognizer "wins" the conflict because its gesture is simpler / more general: A swipe is a pan but a pan may not be a swipe, so the pan recognizes first and excludes other recognizers.</p>
<p>You should be able to resolve this conflict using the delegate method <code>gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:</code>, or perhaps without delegation by making the pan recognizer depend on the swipe recognizer with <code>requireGestureRecognizerToFail:</code>.</p>
<p>With the conflict resolved, you should be able to simulate a one-finger swipe by quickly dragging the mouse. (Though as the mouse is more precise than your finger, it's a bit more finicky than doing the real thing on a device.) Two-finger pan/swipe can be done by holding the Option & Shift keys.</p> |
7,745,578 | "[notice] child pid XXXX exit signal Segmentation fault (11)" in apache error.log | <p>I am using Apache/PHP/MySQL stack.<br>
Using as framework CakePHP. </p>
<p>Every now and then I get a blank white page. I can't debug it through Cake, so I peek in the apache error.log and here's what I get:</p>
<pre><code>[Wed Oct 12 15:27:23 2011] [notice] child pid 3580 exit signal Segmentation fault (11)
[Wed Oct 12 15:27:34 2011] [notice] child pid 3581 exit signal Segmentation fault (11)
[Wed Oct 12 15:30:52 2011] [notice] child pid 3549 exit signal Segmentation fault (11)
[Wed Oct 12 16:04:27 2011] [notice] child pid 3579 exit signal Segmentation fault (11)
zend_mm_heap corrupted
[Wed Oct 12 16:26:24 2011] [notice] child pid 3625 exit signal Segmentation fault (11)
[Wed Oct 12 17:57:24 2011] [notice] child pid 3577 exit signal Segmentation fault (11)
[Wed Oct 12 17:58:54 2011] [notice] child pid 3550 exit signal Segmentation fault (11)
[Wed Oct 12 17:59:52 2011] [notice] child pid 3578 exit signal Segmentation fault (11)
[Wed Oct 12 18:01:38 2011] [notice] child pid 3683 exit signal Segmentation fault (11)
[Wed Oct 12 22:20:53 2011] [notice] child pid 3778 exit signal Segmentation fault (11)
[Wed Oct 12 22:29:51 2011] [notice] child pid 3777 exit signal Segmentation fault (11)
[Wed Oct 12 22:33:42 2011] [notice] child pid 3774 exit signal Segmentation fault (11)
</code></pre>
<p>What is this segmentation fault, and how can I fix it?</p>
<p>UPDATE:</p>
<pre><code>PHP Version 5.3.4, OSX local development
Server version: Apache/2.2.17 (Unix)
CakePhp: 1.3.10
</code></pre> | 7,752,606 | 3 | 5 | null | 2011-10-12 19:38:44.037 UTC | 19 | 2018-05-31 09:15:35.09 UTC | 2018-05-31 09:15:35.09 UTC | null | 13,860 | null | 522,337 | null | 1 | 109 | php|apache|cakephp|error-logging | 206,817 | <p>Attach gdb to one of the httpd child processes and reload or continue working and wait for a crash and then look at the backtrace. Do something like this:</p>
<pre><code>$ ps -ef|grep httpd
0 681 1 0 10:38pm ?? 0:00.45 /Applications/MAMP/Library/bin/httpd -k start
501 690 681 0 10:38pm ?? 0:00.02 /Applications/MAMP/Library/bin/httpd -k start
</code></pre>
<p>...</p>
<p>Now attach gdb to one of the child processes, in this case PID 690 (columns are UID, PID, PPID, ...)</p>
<pre><code>$ sudo gdb
(gdb) attach 690
Attaching to process 690.
Reading symbols for shared libraries . done
Reading symbols for shared libraries ....................... done
0x9568ce29 in accept$NOCANCEL$UNIX2003 ()
(gdb) c
Continuing.
</code></pre>
<p>Wait for crash... then:</p>
<pre><code>(gdb) backtrace
</code></pre>
<p>Or</p>
<pre><code>(gdb) backtrace full
</code></pre>
<p>Should give you some clue what's going on. If you file a bug report you should include the backtrace.</p>
<p>If the crash is hard to reproduce it may be a good idea to configure Apache to only use one child processes for handling requests. The config is something like this:</p>
<pre><code>StartServers 1
MinSpareServers 1
MaxSpareServers 1
</code></pre> |
11,474,684 | Is it possible to insert php variables into your js code? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/7141860/passing-variables-from-php-to-javascript">passing variables from php to javascript</a> </p>
</blockquote>
<p>I'm dynamically generating a list. I want to make each row hover on mouseover and clickable to a link. I want the link to pass the id of the content of the row. </p>
<p>Basically: </p>
<pre><code>foreach ($courses as $cid=>cinfo){
$univ = $cinfo['univ'];
$desc = $cinfo['desc'];
$size = $cinfo['size'];
$start = $cinfo['start'];
print "<div class='rc_desc' id='rc_desc$cid'>"."$desc<br/>"."<b>$univ</b><br/>".
"<span>Number of students</span>: $size<br/>".
"<span>Started at</span>: ".date('F d, Y',strtotime($start))."<br/>".
}
<script>
$(function ()
{
$('#rc_desc$cid').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc$cid').click(function ()
{
$(location).attr('href','student.php?$cid');
});
});
</script>
</code></pre>
<p>The issue is in the js/jquery. I want to be able to grab the $cid and pass it to the student.php page upon click. The php code above works but the js won't of course. I know the fundamental of client-side vs server-side languages. This question doesn't warrant a lecture. I know I cannot do this exactly, but it is what I want to happen ultimately. Any thoughts on how I can achieve this simply? Thanks in advance my friends!</p> | 11,474,725 | 6 | 1 | null | 2012-07-13 16:38:19.503 UTC | 2 | 2012-07-13 17:17:46.607 UTC | 2017-05-23 10:31:09.62 UTC | null | -1 | null | 1,077,914 | null | 1 | 7 | php|javascript|jquery|ajax | 42,921 | <p>Yes, if you include the <code><script></code> section in your PHP code, you can do something similar to the following:</p>
<pre><code><script>
var foo = <?php echo $foo; ?>;
</script>
</code></pre>
<p>In your case, you would be looking into the following code structure:</p>
<pre><code><script>
$(function () {
$('#rc_desc<?php echo $cid ?>').hover(function () {
$(this).toggleClass('.tr');
});
$('#rc_desc<?php echo $cid ?>').click(function () {
$(location).attr('href', 'student.php?<?php echo $cid ?>');
});
});
</script>
</code></pre>
<p>The reason why this is possible is because although the Javascript is run on the client-side, it's processed on the server-side first prior to being presented on the page. Thus, it'll replace all necessary instances of <code>$cid</code> with the one you have included.</p>
<p>Enjoy and good luck!</p>
<p><strong>EDIT</strong>:</p>
<pre><code><script>
$(function () {
$('.rc_desc').hover(function () {
$(this).toggleClass('.tr ');
});
$('.rc_desc').click(function () {
$(location).attr('href', 'student.php?' + $(this).attr('id').split('rc_desc')[1]);
});
});
</script>
</code></pre> |
11,600,213 | Why doesn't java.lang.Object implement the Serializable Interface? | <blockquote>
<p><strong>Possible Duplicate:</strong><br />
<a href="https://stackoverflow.com/questions/441196/why-java-needs-serializable-interface">Why Java needs Serializable interface?</a></p>
</blockquote>
<p>According to Serializability in Java docs :</p>
<blockquote>
<p>Serializability of a class is enabled by the class implementing the
java.io.Serializable interface. Classes that do not implement this
interface will not have any of their state serialized or deserialized.
All subtypes of a serializable class are themselves serializable. The
serialization interface has no methods or fields and serves only to
identify the semantics of being serializable</p>
</blockquote>
<p>Why doesn't the Object already implement <code>Serializable</code>? Members that we wouldn't want to be serializable may be made as <code>transient</code>. Why prevent the default Serializability?</p> | 11,600,227 | 4 | 2 | null | 2012-07-22 12:14:51.307 UTC | 8 | 2022-09-08 13:47:35.673 UTC | 2022-09-08 13:47:35.673 UTC | null | 13,452,926 | null | 174,184 | null | 1 | 38 | java|serializable | 25,722 | <blockquote>
<p>All subtypes of a serializable class are themselves serializable.</p>
</blockquote>
<p>In other words: <strong>all</strong> classes you ever create, were or will be created are all serializable. <code>transient</code> only excludes fields, not whole classes.</p>
<p>This is a potential security hole - by coincidence you can serialize e.g. your <code>DataSource</code> with database credentials inside - if the creator of this particular <code>DataSource</code> implementation forgot to make such fields <code>transient</code>. It's surprisingly easy to serialize random Java object, e.g. through inner classes holding implicit reference to outer <code>this</code>.</p>
<p>It's just safer to use white-list of classes which you explicitly want and allow to serialize as opposed to carefully examining your code, making sure no fields you do not desire are ever serialized.</p>
<p>Moreover you can no longer say: <code>MySuperSecretClass</code> is not serializable (by simply not implementing <code>Serializable</code>) - you can only exclude the guts (fields).</p> |
11,859,437 | how to handle exceptions in JSON based RESTful code? | <p>I have a "software as a service" app that uses JSON communicated via a RESTful API. </p>
<p>Simply stated: what are the best practices for capturing and reporting exceptions when using a RESTful API with JSON data interchange?</p>
<p>My first thought was to see what Rails does by generating a scaffold, but that's clearly not right. Here's an excerpt:</p>
<pre><code>class MumblesController < ApplicationController
# GET /mumbles/1
# GET /mumbles/1.json
def show
@mumble = Mumble.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @mumble }
end
end
end
</code></pre>
<p>In this case, if the JSON code sends a non-existent ID, e.g.</p>
<pre><code>http://www.myhost.com/mumbles/99999.json
</code></pre>
<p>then Mumble.find() will raise ActiveRecord::RecordNotFound. ActionController will catch that and render an error page in HTML. But HTML is useless to the client that is expecting JSON.</p>
<p>I could work around that by wrapping the Mumble.find() in a <code>begin ... rescue RuntimeError</code> block and rendering a JSON status => :unprocessable_entity or something.</p>
<p>But then what if the client's app sends an invalid path, e.g.:</p>
<pre><code>http://www.myhost.com/badtypo/1.json
</code></pre>
<p>Is a JSON based app supposed to catch that and return an error in JSON? If so, where do I capture that without digging deep into ActionDispatch?</p>
<p>So overall, do I punt and let ActionController generate HTML if there's an error? That doesn't feel right...</p> | 11,859,589 | 4 | 0 | null | 2012-08-08 07:12:16.137 UTC | 12 | 2018-11-02 16:53:03.02 UTC | null | null | null | null | 558,639 | null | 1 | 39 | ruby-on-rails|json|actioncontroller | 17,207 | <p>(I found the answer just before I hit [Post your question]. But this might help someone else as well...)</p>
<h2>Use ActionController's <code>rescue_from</code></h2>
<p>The answer is to use ActionController's <code>rescue_from</code>, as described <a href="http://guides.rubyonrails.org/v2.3.11/action_controller_overview.html#rescue" rel="nofollow noreferrer">in this Guide</a> and documented <a href="http://api.rubyonrails.org/classes/ActiveSupport/Rescuable/ClassMethods.html#method-i-rescue_from" rel="nofollow noreferrer">here</a>. In particular, you can replace the default rendering of the default 404.html and 500.html files along these lines:</p>
<pre><code>class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
private
def record_not_found(error)
render :json => {:error => error.message}, :status => :not_found
end
end
</code></pre> |
19,986,662 | Rounding a number in Python but keeping ending zeros | <p>I've been working on a script that takes data from an Excel spreadsheet, rounds the numbers, and removes the decimal point, for example, 2606.89579999999 becomes 26069. However, I need the number to round to two decimal places even if there would be a trailing zero, so 2606.89579999999 should become 260690.</p>
<p>I currently have it so <code>i</code> takes the data from the cell in Excel, and rounds it to two decimal places (<code>i = round(i, 2)</code>) which gives me the single decimal point in the above example.</p>
<p>I've tried figuring out how to get this to work with <code>Decimal</code>, but I can't seem to get it working.</p>
<p>All other numbers that get rounded, if the rounded value doesn't end in '0', work fine with <code>round(i, 2)</code>, but if the numbers just so happen to end in *.x0, that 0 gets dropped off and messes with the data.</p> | 19,986,686 | 6 | 4 | null | 2013-11-14 19:32:41.63 UTC | 13 | 2022-05-05 22:27:32.443 UTC | 2018-10-20 00:04:39.19 UTC | null | 63,550 | null | 2,917,582 | null | 1 | 52 | python|floating-point|decimal|rounding | 102,995 | <p>As you are talking about trailing zeros, this is a question about representation as string,
you can use</p>
<pre><code>>>> "%.2f" % round(2606.89579999999, 2)
'2606.90'
</code></pre>
<p>Or use modern style with <code>format</code> function:</p>
<pre><code>>>> '{:.2f}'.format(round(2606.89579999999, 2))
'2606.90'
</code></pre>
<p>and remove point with <code>replace</code> or <code>translate</code> (<code>_</code> refers to result of previous command in python console):</p>
<pre><code>>>> _.translate(None, '.')
'260690'
</code></pre>
<p>Note that rounding is not needed here, as <code>.2f</code> format applyies the same rounding:</p>
<pre><code>>>> "%.2f" % 2606.89579999999
'2606.90'
</code></pre>
<p>But as you mentioned excel, you probably would opt to roll your own rounding function, or use <a href="http://docs.python.org/2/library/decimal.html" rel="noreferrer">decimal</a>, as <code>float.round</code> can lead to strange results due to float representation:</p>
<pre><code>>>> round(2.675, 2)
2.67
>>> round(2606.89579999999, 2)
2606.89
</code></pre>
<p>With decimal use <a href="http://docs.python.org/2/library/decimal.html#decimal.Decimal.quantize" rel="noreferrer">quantize</a>:</p>
<pre><code>>>> from decimal import *
>>> x = Decimal('2606.8950000000001')
# Decimal('2606.8950000000001')
>>> '{}'.format(x.quantize(Decimal('.01'), rounding=ROUND_HALF_EVEN))
'2606.90'
</code></pre>
<p>That, for your original task, becomes:</p>
<pre><code>>>> x = Decimal('2606.8950000000001')
>>> int((x*100).quantize(1, rounding=ROUND_HALF_EVEN))
260690
</code></pre>
<p>And the reason of strange rounding comes to the front with <code>Decimal</code>:</p>
<pre><code>>>> x = Decimal(2606.8950000000001)
# Decimal('2606.89499999999998181010596454143524169921875') # internal float repr
</code></pre> |
61,550,004 | Check if string contains any letter (Javascript/jquery) | <p>How can i check if a string contains any letter in javascript?</p>
<p>Im currently using this to check if string contains any numbers:</p>
<pre><code> jQuery(function($){
$('body').on('blur change', '#billing_first_name', function(){
var wrapper = $(this).closest('.form-row');
// you do not have to removeClass() because Woo do it in checkout.js
if( /\d/.test( $(this).val() ) ) { // check if contains numbers
wrapper.addClass('woocommerce-invalid'); // error
} else {
wrapper.addClass('woocommerce-validated'); // success
}
});
});
</code></pre>
<p>However i want it to see if it contains any letters.</p> | 61,550,284 | 5 | 4 | null | 2020-05-01 20:08:09.267 UTC | 3 | 2022-05-25 19:58:18.003 UTC | null | null | null | null | 13,144,006 | null | 1 | 23 | javascript|jquery|wordpress|woocommerce | 50,190 | <p>You have to use Regular Expression to check that :-</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var regExp = /[a-zA-Z]/g;
var testString = "john";
if(regExp.test(testString)){
/* do something if letters are found in your string */
} else {
/* do something if letters are not found in your string */
}</code></pre>
</div>
</div>
</p> |
3,639,859 | Handling applicationDidBecomeActive - "How can a view controller respond to the app becoming Active?" | <p>I have the <code>UIApplicationDelegate</code> protocol in my main AppDelegate.m class, with the <code>applicationDidBecomeActive</code> method defined. </p>
<p>I want to call a method when the application returns from the background, but the method is in another view controller. How can I check which view controller is currently showing in the <code>applicationDidBecomeActive</code> method and then make a call to a method within that controller?</p> | 3,639,903 | 12 | 0 | null | 2010-09-03 22:01:57.29 UTC | 51 | 2022-08-18 08:22:43.2 UTC | 2014-03-16 05:33:08.477 UTC | null | 470,879 | null | 138,261 | null | 1 | 191 | ios|iphone|ios4|multitasking|uiapplicationdelegate | 104,352 | <p>Any class in your application can become an "observer" for different notifications in the application. When you create (or load) your view controller, you'll want to register it as an observer for the <code>UIApplicationDidBecomeActiveNotification</code> and specify which method that you want to call when that notification gets sent to your application.</p>
<pre><code>[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(someMethod:)
name:UIApplicationDidBecomeActiveNotification object:nil];
</code></pre>
<p>Don't forget to clean up after yourself! Remember to remove yourself as the observer when your view is going away:</p>
<pre><code>[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIApplicationDidBecomeActiveNotification
object:nil];
</code></pre>
<p>More information about the <a href="https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Notifications/Articles/NotificationCenters.html#//apple_ref/doc/uid/20000216-BAJGDAFC" rel="noreferrer">Notification Center</a>.</p> |
8,163,852 | Should I avoid using Monad fail? | <p>I'm fairly new to Haskell and have been slowly getting the idea that there's something wrong with the existence of Monad fail. Real World Haskell <a href="http://book.realworldhaskell.org/read/monad-transformers.html#x_Et" rel="noreferrer">warns against its use</a> ("Once again, we recommend that you almost always avoid using fail!"). I just noticed today that Ross Paterson called it "a wart, not a design pattern" <a href="http://haskell.1045720.n5.nabble.com/Proposal-Add-Text-Read-maybeRead-Read-a-gt-String-gt-Maybe-a-td3174167.html" rel="noreferrer">back in 2008</a> (and seemed to get quite some agreement in that thread).</p>
<p>While watching Dr Ralf Lämmel <a href="http://channel9.msdn.com/Shows/Going+Deep/C9-Lectures-Dr-Ralf-Lmmel-AFP-The-Quick-Essence-of-Functional-Programming" rel="noreferrer">talk on the essence of functional programming</a>, I started to understand a possible tension which may have led to Monad fail. In the lecture, Ralf talks about adding various monadic effects to a base monadic parser (logging, state etc). Many of the effects required changes to the base parser and sometimes the data types used. I figured that the addition of 'fail' to all monads might have been a compromise because 'fail' is so common and you want to avoid changes to the 'base' parser (or whatever) as much as possible. Of course, some kind of 'fail' makes sense for parsers but not always, say, put/get of State or ask/local of Reader.</p>
<p>Let me know if I could be off onto the wrong track.</p>
<p>Should I avoid using Monad fail?
What are the alternatives to Monad fail?
Are there any alternative monad libraries that do not include this "design wart"?
Where can I read more about the history around this design decision?</p> | 8,165,550 | 4 | 4 | null | 2011-11-17 08:05:02.293 UTC | 5 | 2022-02-04 08:19:10.77 UTC | 2014-01-07 15:03:36.723 UTC | null | 707,111 | null | 482,382 | null | 1 | 39 | monads|haskell | 9,928 | <p>Some monads have a sensible failure mechanism, e.g. the terminal monad:</p>
<pre><code>data Fail x = Fail
</code></pre>
<p>Some monads don't have a sensible failure mechanism (<code>undefined</code> is not sensible), e.g. the initial monad:</p>
<pre><code>data Return x = Return x
</code></pre>
<p>In that sense, it's clearly a wart to require all monads to have a <code>fail</code> method. If you're writing programs that abstract over monads <code>(Monad m) =></code>, it's not very healthy to make use of that generic <code>m</code>'s <code>fail</code> method. That would result in a function you can instantiate with a monad where <code>fail</code> shouldn't really exist.</p>
<p>I see fewer objections to using <code>fail</code> (especially indirectly, by matching <code>Pat <- computation</code>) when working in a specific monad for which a good <code>fail</code> behaviour has been clearly specified. Such programs would hopefully survive a return to the old discipline where nontrivial pattern matching created a demand for <code>MonadZero</code> instead of just <code>Monad</code>.</p>
<p>One might argue that the better discipline is always to treat failure-cases explicitly. I object to this position on two counts: (1) that the point of monadic programming is to avoid such clutter, and (2) that the current notation for case analysis on the result of a monadic computation is so awful. The next release of SHE will support the notation (also found in other variants)</p>
<pre><code>case <- computation of
Pat_1 -> computation_1
...
Pat_n -> computation_n
</code></pre>
<p>which might help a little.</p>
<p>But this whole situation is a sorry mess. It's often helpful to characterize monads by the operations which they support. You can see <code>fail</code>, <code>throw</code>, etc as operations supported by some monads but not others. Haskell makes it quite clumsy and expensive to support small localized changes in the set of operations available, introducing new operations by explaining how to handle them in terms of the old ones. If we seriously want to do a neater job here, we need to rethink how <code>catch</code> works, to make it a translator between <em>different</em> local error-handling mechanisms. I often want to bracket a computation which can fail uninformatively (e.g. by pattern match failure) with a handler that adds more contextual information before passing on the error. I can't help feeling that it's sometimes more difficult to do that than it should be.</p>
<p>So, this is a could-do-better issue, but at the very least, use <code>fail</code> only for specific monads which offer a sensible implementation, and handle the 'exceptions' properly.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.