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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
45,818,937 | webpack : Uncaught ReferenceError: require is not defined | <p>This error comes when in webpack <code>target = node</code> but i have done <code>target=web</code>(default)</p>
<p>also i am not loading reactjs externally </p>
<p>this error comes on loading app in browser</p>
<p><strong>what i am doing wrong ?</strong></p>
<p><strong>In Console</strong></p>
<p><a href="https://i.stack.imgur.com/VyCEW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VyCEW.png" alt="enter image description here"></a></p>
<p><strong>File</strong></p>
<p><a href="https://i.stack.imgur.com/7cw5x.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7cw5x.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/tUaYh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tUaYh.png" alt="enter image description here"></a></p>
<p><strong>webpack.config.js</strong></p>
<pre><code>const HtmlWebpackPlugin = require('html-webpack-plugin');
const nodeExternals = require('webpack-node-externals');
const config = {
target: 'web',
externals: [nodeExternals()],
entry: './src/index.js',
output: {
filename: '[name].bundle.js',
path: __dirname + '/build'
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
},
{
test: /\.(png|svg|jpe?g|gif)$/,
use: [{
loader: 'file-loader',
options: {
name: '[path][name].[ext]'
}
}
]
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: ['file-loader']
}
]
},
devtool: 'inline-source-map',
plugins: [
new HtmlWebpackPlugin({
title: 'Instarem.com'
})
]
};
module.exports = config;
</code></pre>
<p><strong>.babelrc</strong> using </p>
<h2><code>babel-preset-env</code></h2>
<pre><code>{
"presets": [
"react",
[
"env",
{
"targets": {
"browsers": ["last 2 versions"]
},
"debug": true,
"modules": "commonjs"
}
]
],
"plugins": [
"transform-object-rest-spread",
"transform-class-properties"
]
}
</code></pre>
<p>thanks :)</p>
<blockquote>
<p><strong>I found Clue</strong></p>
</blockquote>
<hr>
<p><em>In facebook's <strong><a href="https://github.com/facebookincubator/create-react-app" rel="noreferrer">create react app generator</a></strong> bundle it shows</em></p>
<pre><code>module.exports = __webpack_require__(/*! ./lib/React */ "./node_modules/react/lib/React.js");
</code></pre>
<p><em>but in my case it shows only</em></p>
<pre><code>module.exports = require("react");
</code></pre> | 45,820,235 | 6 | 0 | null | 2017-08-22 13:25:22.78 UTC | 4 | 2022-02-09 18:53:37.553 UTC | 2017-08-22 14:27:19.037 UTC | null | 1,390,678 | null | 1,390,678 | null | 1 | 33 | javascript|reactjs|webpack|ecmascript-6|babeljs | 46,960 | <p>You should not use </p>
<pre><code>externals: [nodeExternals()],
</code></pre>
<p>in web app. According to <a href="https://github.com/liady/webpack-node-externals" rel="noreferrer">https://github.com/liady/webpack-node-externals</a> it is only for backend. Since you use <code>nodeExternals</code> in web app you get CommonJS modules, that expects built in node <code>require</code> function. So just remove it to fix error.</p> |
42,611,880 | Difference between await for and listen in Dart | <p>I am trying to create a web server stream. Here is the code:</p>
<pre><code>import 'dart:io';
main() async {
HttpServer requestServer = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8000);
requestServer.listen((request) { //comment out this or the await for to work
request.response
..write("This is a listen stream")
..close();
});
await for (HttpRequest request in requestServer) {
request.response
..write("This is an await for stream")
..close();
}
}
</code></pre>
<p>What is the difference between listen and await for? They both do not work at the same time. You need to comment out one or the other to work, but there doesn't seem to be a difference in function here. Are there circumstances where there is a difference, and when should you use one over the other?</p> | 42,613,676 | 5 | 0 | null | 2017-03-05 17:54:09.023 UTC | 5 | 2021-09-20 18:20:07.54 UTC | null | null | null | null | 3,332,878 | null | 1 | 34 | stream|async-await|dart|listen | 10,556 | <p>Given:</p>
<pre><code>Stream<String> stream = new Stream<String>.fromIterable(['mene', 'mene', 'tekel', 'parsin']);
</code></pre>
<p>then:</p>
<pre><code>print('BEFORE');
stream.listen((s) { print(s); });
print('AFTER');
</code></pre>
<p>yields:</p>
<pre><code>BEFORE
AFTER
mene
mene
tekel
parsin
</code></pre>
<p>whereas:</p>
<pre><code>print('BEFORE');
await for(String s in stream) { print(s); }
print('AFTER');
</code></pre>
<p>yields:</p>
<pre><code>BEFORE
mene
mene
tekel
parsin
AFTER
</code></pre>
<p><code>stream.listen()</code> sets up code that will be put on the event queue when an event arrives, then following code is executed.</p>
<p><code>await for</code> suspends between events and keeps doing so <em>until the stream is done</em>, so code following it will not be executed until that happens. </p>
<p>I use `await for when I have a stream that I know will have finite events, and I need to process them before doing anything else (essentially as if I'm dealing with a list of futures).</p>
<p>Check <a href="https://www.dartlang.org/articles/language/beyond-async" rel="noreferrer">https://www.dartlang.org/articles/language/beyond-async</a> for a description of <code>await for</code>.</p> |
31,845,895 | How to build/concatenate strings in JavaScript? | <p>Does JavaScript support substitution/interpolation?</p>
<h1>Overview</h1>
<hr />
<p>I'm working on a JS project, and as it's getting bigger, keeping strings in good shape is getting a lot harder. I'm wondering what's the easiest and most conventional way to construct or build strings in JavaScript.</p>
<p>My experience so far:</p>
<blockquote>
<p>String concatenation starts looking ugly and becomes harder to maintain as the project becomes more complex.</p>
</blockquote>
<p>The most important this at this point is succinctness and readability, think a bunch of moving parts, not just 2-3 variables.</p>
<p>It's also important that it's supported by major browsers as of today (i.e at least ES5 supported).</p>
<p>I'm aware of the JS concatenation shorthand:</p>
<pre><code>var x = 'Hello';
var y = 'world';
console.log(x + ', ' + y);
</code></pre>
<p>And of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat" rel="nofollow noreferrer">String.concat</a> function.</p>
<p>I'm looking for something a bit neater.</p>
<p>Ruby and Swift do it in an interesting way.</p>
<p><strong>Ruby</strong></p>
<pre><code>var x = 'Hello'
var y = 'world'
print "#{x}, #{y}"
</code></pre>
<p><strong>Swift</strong></p>
<pre><code>var x = "Hello"
var y = "world"
println("\(x), \(y)")
</code></pre>
<p>I was thinking that there might be something like that in JavaScript maybe something similar to <a href="https://github.com/alexei/sprintf.js" rel="nofollow noreferrer">sprintf.js</a>.</p>
<h1>Question</h1>
<hr />
<p>Can this be done without any third party library? If not, what can I use?</p> | 31,845,980 | 7 | 0 | null | 2015-08-06 02:33:39.243 UTC | 2 | 2022-06-18 20:06:26.297 UTC | 2022-06-18 20:06:26.297 UTC | null | 2,803,660 | null | 2,803,660 | null | 1 | 65 | javascript|string|concatenation|conventions | 95,097 | <p>With ES6, you can use </p>
<ul>
<li><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings" rel="noreferrer">Template strings</a>:</p>
<pre><code>var username = 'craig';
console.log(`hello ${username}`);
</code></pre></li>
</ul>
<p>ES5 and below:</p>
<ul>
<li><p>use the <code>+</code> operator</p>
<pre><code>var username = 'craig';
var joined = 'hello ' + username;
</code></pre></li>
<li><p>String's <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat" rel="noreferrer"><code>concat(..)</code></a></p>
<pre><code>var username = 'craig';
var joined = 'hello '.concat(username);
</code></pre></li>
</ul>
<p>Alternatively, use Array methods:</p>
<ul>
<li><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join" rel="noreferrer"><code>join(..)</code></a>:</p>
<pre><code>var username = 'craig';
var joined = ['hello', username].join(' ');
</code></pre></li>
<li><p>Or even fancier, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce" rel="noreferrer"><code>reduce(..)</code></a> combined with any of the above:</p>
<pre><code>var a = ['hello', 'world', 'and', 'the', 'milky', 'way'];
var b = a.reduce(function(pre, next) {
return pre + ' ' + next;
});
console.log(b); // hello world and the milky way
</code></pre></li>
</ul> |
31,875,810 | C# method naming conventions: ToSomething vs. AsSomething | <p>As I was writing some extension methods for my business logic objects, I came to the question of renaming the conversion methods. <code>someObject.ToAnotherObject()</code> would go fine with the widely used <code>object.ToString()</code>.</p>
<p>However LINQ, for example, mixes up both variants and I can't find a difference between them. <code>ToDictionary()</code>, <code>ToList()</code>, <code>AsParallel()</code>, <code>AsQueryable()</code>, ...</p>
<p>What are the differences between these two naming conventions and what should I know to decide whether to use for my own classes?</p> | 31,875,903 | 2 | 0 | null | 2015-08-07 10:43:49.967 UTC | 5 | 2015-08-14 12:09:38.04 UTC | 2015-08-14 12:09:38.04 UTC | null | 128,002 | null | 3,414,957 | null | 1 | 83 | c#|naming-conventions | 2,426 | <p><code>ToDictionary</code> and <code>ToList</code> are prefixed with <code>To</code> because they don't necessarily preserve the structural identity of the original collection or its properties.</p>
<ul>
<li>Transforming a <code>List<T></code> into a <code>Dictionary<K, V></code> creates a collection with a whole new structure.</li>
<li>Transforming a <code>HashSet<T></code> into a <code>List<T></code> removes the uniqueness property of sets.</li>
</ul>
<p>Methods prefixed with <code>As</code> don't do any of these things - they simply provide an alternative <em>view</em> of the original collection. They enrich it.</p> |
25,973,046 | Printing to POS printer from PHP | <p>We are looking to print to a POS printer connected where apache is running. Due to design of the application, and deployment, printing should be done from Server (it should detect the order and send to different printers and different formats of printing...bill, kitchen orders, and so on...). For this reason and others (like access application from an iPad for example) we discard options like QZ-Print applet and needst o print directly server side.</p>
<p>We searched a lot, and found that there are an extension called php-printer but seems outdated, and just works under WIndows.</p>
<p>We followed this code: (<a href="http://mocopat.wordpress.com/2012/01/18/php-direct-printing-printer-dot-matrix-lx-300/" rel="noreferrer">http://mocopat.wordpress.com/2012/01/18/php-direct-printing-printer-dot-matrix-lx-300/</a>)</p>
<pre><code>$tmpdir = sys_get_temp_dir(); # ambil direktori temporary untuk simpan file.
$file = tempnam($tmpdir, 'ctk'); # nama file temporary yang akan dicetak
$handle = fopen($file, 'w');
$condensed = Chr(27) . Chr(33) . Chr(4);
$bold1 = Chr(27) . Chr(69);
$bold0 = Chr(27) . Chr(70);
$initialized = chr(27).chr(64);
$condensed1 = chr(15);
$condensed0 = chr(18);
$corte = Chr(27) . Chr(109);
$Data = $initialized;
$Data .= $condensed1;
$Data .= "==========================\n";
$Data .= "| ".$bold1."OFIDZ MAJEZTY".$bold0." |\n";
$Data .= "==========================\n";
$Data .= "Ofidz Majezty is here\n";
$Data .= "We Love PHP Indonesia\n";
$Data .= "We Love PHP Indonesia\n";
$Data .= "We Love PHP Indonesia\n";
$Data .= "We Love PHP Indonesia\n";
$Data .= "We Love PHP Indonesia\n";
$Data .= "--------------------------\n";
$Data .= $corte;
fwrite($handle, $Data);
fclose($handle);
copy($file, "//localhost/KoTickets"); # Lakukan cetak
unlink($file);
</code></pre>
<p>And it works, but this sends plain text, and we need to send image (logo), and format a more cute bill. We tried creating a PDF and "sending" to the printer in the same way, but just prints blank.</p>
<p>I found a library to work with network printers (escpos-php on github), but we need to work with USB printers too, to avoid our customers to change hardware.</p>
<p>Some ideas how to achieve this?</p>
<p>Thanks in advance.</p> | 29,059,186 | 1 | 0 | null | 2014-09-22 11:29:50.833 UTC | 27 | 2021-04-13 08:13:57.73 UTC | null | null | null | null | 1,590,069 | null | 1 | 23 | php|printing|kiosk | 127,492 | <p>Author of <a href="https://github.com/mike42/escpos-php">escpos-php</a> here.</p>
<p>If your printers do support ESC/POS (most thermal receipt printers seem to use some sub-set of it), then I think the driver will accommodate your use case: USB or network printing, logo, some formatting. Some of these are quite recent additions.</p>
<h2>USB printing</h2>
<p>escpos-php prints to a file pointer. On Linux, you can make the USB printer visible as a a file using the <code>usblp</code> driver, and then just <code>fopen()</code> it (<a href="https://github.com/mike42/escpos-php/blob/master/example/interface/linux-usb.php">USB receipt example</a>, <a href="http://mike.bitrevision.com/blog/2015-03-getting-a-usb-receipt-printer-working-on-linux">blog post about installing a USB printer on Linux</a>).</p>
<p>So printing "Hello world" on a USB printer is only slightly different to printing to a networked printer:</p>
<pre><code><?php
require __DIR__ . '/vendor/autoload.php';
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\Printer;
$connector = new FilePrintConnector("/dev/usb/lp0");
$printer = new Printer($connector);
$printer -> text("Hello World!\n");
$printer -> cut();
$printer -> close();
</code></pre>
<p>Or, more like the code you are currently using successfully, you could write to a temp file and copy it:</p>
<pre><code><?php
require __DIR__ . '/vendor/autoload.php';
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\Printer;
/* Open file */
$tmpdir = sys_get_temp_dir();
$file = tempnam($tmpdir, 'ctk');
/* Do some printing */
$connector = new FilePrintConnector($file);
$printer = new Printer($connector);
$printer -> text("Hello World!\n");
$printer -> cut();
$printer -> close();
/* Copy it over to the printer */
copy($file, "//localhost/KoTickets");
unlink($file);
</code></pre>
<p>So in your POS system, you would need a function which returns a file pointer based on your customer configuration and preferred destination. Receipt printers respond quite quickly, but if you have a few iPads making orders, you should wrap operations to each printer with a file lock (<a href="http://php.net/manual/en/function.flock.php">flock()</a>) to avoid concurrency-related trouble.</p>
<p>Also note that USB support on Windows is un-tested.</p>
<h2>Logo & Formatting</h2>
<p>Once you have figured out how you plan to talk to the printer, you can use the full suite of formatting and image commands.</p>
<p>A logo can be printed from a PNG file like so:</p>
<pre><code>use Mike42\Escpos\EscposImage;
$logo = EscposImage::load("foo.png");
$printer -> graphics($logo);
</code></pre>
<p>And for formatting, the <a href="https://github.com/mike42/escpos-php/blob/master/README.md">README.md</a> and the example below should get you started. For most receipts, you only really need:</p>
<ul>
<li><code>selectPrintMode()</code> to alter font sizes.</li>
<li><code>setEmphasis()</code> to toggle bold.</li>
<li><code>setJustification()</code> to left-align or center some text or images.</li>
<li><code>cut()</code> after each receipt.</li>
</ul>
<p>I would also suggest that where you are currently using an example that draws boxes like this:</p>
<pre><code>=========
| |
=========
</code></pre>
<p>You could make use of the characters in IBM <a href="http://en.wikipedia.org/wiki/Code_page_437">Code page 437</a> which are designed for drawing boxes that are supported by many printers- just include characters 0xB3 to 0xDA in the output. They aren't perfect, but it looks a lot less "text"-y.</p>
<pre><code>$box = "\xda".str_repeat("\xc4", 10)."\xbf\n";
$box .= "\xb3".str_repeat(" ", 10)."\xb3\n";
$box .= "\xc0".str_repeat("\xc4", 10)."\xd9\n";
$printer -> textRaw($box);
</code></pre>
<h2>Full example</h2>
<p>The below example is <a href="https://github.com/mike42/escpos-php/blob/master/example/receipt-with-logo.php">also now included</a> with the driver. I think it looks like a fairly typical store receipt, formatting-wise, and could be easily adapted to your kitchen scenario.</p>
<p>Scanned output:</p>
<p><img src="https://i.stack.imgur.com/B4Owl.png" alt="Example formatted receipt including logo"></p>
<p>PHP source code to generate it:</p>
<pre><code><?php
require __DIR__ . '/vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\EscposImage;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
/* Open the printer; this will change depending on how it is connected */
$connector = new FilePrintConnector("/dev/usb/lp0");
$printer = new Printer($connector);
/* Information for the receipt */
$items = array(
new item("Example item #1", "4.00"),
new item("Another thing", "3.50"),
new item("Something else", "1.00"),
new item("A final item", "4.45"),
);
$subtotal = new item('Subtotal', '12.95');
$tax = new item('A local tax', '1.30');
$total = new item('Total', '14.25', true);
/* Date is kept the same for testing */
// $date = date('l jS \of F Y h:i:s A');
$date = "Monday 6th of April 2015 02:56:25 PM";
/* Start the printer */
$logo = EscposImage::load("resources/escpos-php.png", false);
$printer = new Printer($connector);
/* Print top logo */
$printer -> setJustification(Printer::JUSTIFY_CENTER);
$printer -> graphics($logo);
/* Name of shop */
$printer -> selectPrintMode(Printer::MODE_DOUBLE_WIDTH);
$printer -> text("ExampleMart Ltd.\n");
$printer -> selectPrintMode();
$printer -> text("Shop No. 42.\n");
$printer -> feed();
/* Title of receipt */
$printer -> setEmphasis(true);
$printer -> text("SALES INVOICE\n");
$printer -> setEmphasis(false);
/* Items */
$printer -> setJustification(Printer::JUSTIFY_LEFT);
$printer -> setEmphasis(true);
$printer -> text(new item('', '$'));
$printer -> setEmphasis(false);
foreach ($items as $item) {
$printer -> text($item);
}
$printer -> setEmphasis(true);
$printer -> text($subtotal);
$printer -> setEmphasis(false);
$printer -> feed();
/* Tax and total */
$printer -> text($tax);
$printer -> selectPrintMode(Printer::MODE_DOUBLE_WIDTH);
$printer -> text($total);
$printer -> selectPrintMode();
/* Footer */
$printer -> feed(2);
$printer -> setJustification(Printer::JUSTIFY_CENTER);
$printer -> text("Thank you for shopping at ExampleMart\n");
$printer -> text("For trading hours, please visit example.com\n");
$printer -> feed(2);
$printer -> text($date . "\n");
/* Cut the receipt and open the cash drawer */
$printer -> cut();
$printer -> pulse();
$printer -> close();
/* A wrapper to do organise item names & prices into columns */
class item
{
private $name;
private $price;
private $dollarSign;
public function __construct($name = '', $price = '', $dollarSign = false)
{
$this -> name = $name;
$this -> price = $price;
$this -> dollarSign = $dollarSign;
}
public function __toString()
{
$rightCols = 10;
$leftCols = 38;
if ($this -> dollarSign) {
$leftCols = $leftCols / 2 - $rightCols / 2;
}
$left = str_pad($this -> name, $leftCols) ;
$sign = ($this -> dollarSign ? '$ ' : '');
$right = str_pad($sign . $this -> price, $rightCols, ' ', STR_PAD_LEFT);
return "$left$right\n";
}
}
</code></pre> |
28,270,618 | What is Main difference between @api.onchange and @api.depends in Odoo(openerp)? | <p>In Odoo v8 there are many API decorators used. But I don't understand the main difference between <code>@api.depends</code> and <code>@api.onchange</code>.</p>
<p>Can anyone help me out from this one?</p>
<p>Thank You.</p> | 28,271,412 | 3 | 0 | null | 2015-02-02 03:11:12.333 UTC | 15 | 2021-09-15 00:06:46.183 UTC | 2021-09-15 00:06:46.183 UTC | null | 9,134,517 | null | 4,122,020 | null | 1 | 33 | odoo|odoo-8 | 30,505 | <p><strong>@api.depends</strong></p>
<p>This decorator is specifically used for "fields.function" in odoo. For a "field.function", you can calculate the value and store it in a field, where it may possible that the calculation depends on some other field(s) of same table or some other table, in that case you can use '@api.depends' to keep a 'watch' on a field of some table. </p>
<p>So, this will trigger the call to the decorated function if any of the fields in the decorator is <strong>'altered by ORM or changed in the form'</strong>.</p>
<p><strong>Let's say there is a table 'A' with fields "x,y & z" and table 'B' with fields "p", where 'p' is a field.function depending upon the field 'x' from table 'A', so if any of the change is made in the field 'x', it will trigger the decorated function for calculating the field 'p' in table 'B'.</strong></p>
<p>Make sure table "A" and "B" are related in some way.</p>
<p><strong>@api.onchange</strong></p>
<p>This decorator will trigger the call to the decorated function if any of the fields specified in the decorator is changed in the form. <strong>Here scope is limited to the same screen / model.</strong> </p>
<p>Let's say on form we have fields "DOB" and "Age", so we can have @api.onchange decorator for "DOB", where as soon as you change the value of "DOB", you can calculate the "age" field. </p>
<p>You may field similarities in @api.depends and @api.onchange, but the some differences are that scope of onchange is limited to the same screen / model while @api.depends works other related screen / model also. </p>
<p>For more info, <a href="http://odoo-new-api-guide-line.readthedocs.org/en/latest/decorator.html">Here</a> is the link that describe all API of Odoo v8.</p> |
2,533,502 | Rails 3: Validate combined values | <p>In Rails 2.x you can use validations to make sure you have a unique combined value like this:</p>
<pre><code>validates_uniqueness_of :husband, :scope => :wife
</code></pre>
<p>In the corresponding migration it could look like this:</p>
<pre><code>add_index :family, [:husband, :wife], :unique => true
</code></pre>
<p>This would make sure the husband/wife combination is unique in the database. Now, in Rails 3 the validation syntax changed and the scope attribute seems to be gone. It now looks like:</p>
<pre><code>validates :husband, :presence => true
</code></pre>
<p>Any idea how I can achieve the combined validation in Rails 3? The Rails 2.x validations still work in Rails 3 so I can still use the first example but it looks so "old", are there better ways?</p> | 2,533,615 | 1 | 0 | null | 2010-03-28 15:54:25.7 UTC | 12 | 2010-03-28 16:50:35.377 UTC | null | null | null | null | 59,991 | null | 1 | 40 | ruby-on-rails|ruby-on-rails-3|validation|validates-uniqueness-of|database-integrity | 20,111 | <p>Bear with me. The way the validates method in ActiveModel works is to look for a Validator.</p>
<p><code>:presence => true</code> looks for <code>PresenceValidator</code> and passes the options: <code>true</code> to the validator's initializer.</p>
<p>I think you want </p>
<pre><code>validates :husband, :presence => true, :uniqueness => {:scope => :wife}
</code></pre>
<p>(The uniqueness validator is actually part of ActiveRecord, not ActiveModel. It's really interesting how the developers set this up. It's quite elegant.)</p> |
37,471,313 | setup_requires with Cython? | <p>I'm creating a <code>setup.py</code> file for a project with some Cython extension modules.</p>
<p>I've already gotten this to work:</p>
<pre><code>from setuptools import setup, Extension
from Cython.Build import cythonize
setup(
name=...,
...,
ext_modules=cythonize([ ... ]),
)
</code></pre>
<p>This installs fine. However, this assumes Cython is installed. What if it's not installed? I understand this is what the <code>setup_requires</code> parameter is for:</p>
<pre><code>from setuptools import setup, Extension
from Cython.Build import cythonize
setup(
name=...,
...,
setup_requires=['Cython'],
...,
ext_modules=cythonize([ ... ]),
)
</code></pre>
<p>However, if Cython isn't already installed, this will of course fail:</p>
<pre><code>$ python setup.py install
Traceback (most recent call last):
File "setup.py", line 2, in <module>
from Cython.Build import cythonize
ImportError: No module named Cython.Build
</code></pre>
<p>What's the proper way to do this? I need to somehow import <code>Cython</code> only after the <code>setup_requires</code> step runs, but I need <code>Cython</code> in order to specify the <code>ext_modules</code> values.</p> | 37,471,428 | 3 | 0 | null | 2016-05-26 21:28:16.263 UTC | 7 | 2020-07-14 09:19:37.07 UTC | null | null | null | null | 15,055 | null | 1 | 30 | python|build|cython|setuptools|software-distribution | 11,321 | <p>You must wrap the <code>from Cython.Build import cythonize</code> in a <code>try-except</code>, and in the <code>except</code>, define <code>cythonize</code> as a dummy function. This way the script can be loaded without failing with an <code>ImportError</code>.</p>
<p>Then later when the <code>setup_requires</code> argument is handled, <code>Cython</code> will be installed and the setup script will be re-executed. Since at that point <code>Cython</code> is installed, you'll be able to successfully import <code>cythonize</code></p>
<pre><code>try:
from Cython.Build import cythonize
except ImportError:
def cythonize(*args, **kwargs):
from Cython.Build import cythonize
return cythonize(*args, **kwargs)
</code></pre>
<p>EDIT</p>
<p>As noted in comments, after setuptools deals with missing dependencies, it won't re-load Cython. I hadn't thought of it before, but you could also try a late-binding approach to stubbing out <code>cythonize</code></p> |
51,263,768 | gem install - fatal error: 'ruby/config.h' file not found in Mojave | <p>gem install is failing in MacOs Mojave. Anything that can help me solve this? My ruby version is <code>ruby 2.3.7p456</code>. </p>
<pre><code>➜ sudo gem install json -v '1.8.3'
current directory: /Library/Ruby/Gems/2.3.0/gems/json-1.8.3/ext/json/ext/generator
make "DESTDIR="
compiling generator.c
In file included from generator.c:1:
In file included from ./../fbuffer/fbuffer.h:5:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/include/ruby-2.3.0/ruby.h:33:
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/include/ruby-2.3.0/ruby/ruby.h:24:10: fatal error: 'ruby/config.h' file not found
#include "ruby/config.h"
^~~~~~~~~~~~~~~
1 error generated.
make: *** [generator.o] Error 1
make failed, exit code 2
</code></pre> | 51,267,506 | 8 | 0 | null | 2018-07-10 11:15:13.36 UTC | 5 | 2022-02-11 18:52:40.857 UTC | 2018-07-10 11:52:00.96 UTC | null | 57,135 | null | 2,487,058 | null | 1 | 32 | ruby|macos|macos-mojave | 21,046 | <p>If you have the Xcode 10 beta running this might fix it</p>
<pre><code>sudo xcode-select -s /Applications/Xcode-beta.app/Contents/Developer
</code></pre> |
18,715,955 | Bootstrap grid with fixed wrapper - Prevent columns from stacking up | <p>As the title says I'm trying to use Bootstrap 3 grid system with a fixed wrapper. But when I resize the Browser the columns stack up even if the wrapper stays the same size?</p>
<p>BTW: I'm using version 3 so that I can move to a responsive layout after I have ported the site. (Which is huge and I'm alone, so step by step is the only option ...)</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Bootstrap 101 Template</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="../../assets/js/html5shiv.js"></script>
<script src="../../assets/js/respond.min.js"></script>
<![endif]-->
<style>
/* Custom container */
.container-fixed {
margin: 0 auto;
max-width: 800px;
min-width: 800px;
width: 800px;
background-color:#C05659;
}
.container-fixed > hr {
margin: 30px 0;
}
</style>
</head>
<body>
<div class="container-fixed">
<div class="row">
<div class="col-md-4">.col-md-4</div>
<div class="col-md-4">.col-md-4</div>
<div class="col-md-4">.col-md-4</div>
</div>
<hr>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="http://code.jquery.com/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
</body>
</html>
</code></pre> | 18,717,422 | 1 | 0 | null | 2013-09-10 10:03:48.367 UTC | 5 | 2021-01-28 03:06:20.447 UTC | 2021-01-28 03:06:20.447 UTC | null | 117,259 | null | 524,290 | null | 1 | 27 | css|twitter-bootstrap|grid|web-deployment|twitter-bootstrap-3 | 57,385 | <p>The <code>sm</code>,<code>md</code>,<code>lg</code>,etc.. cols wrap/stack responsively. Use the <strong>non-stacking</strong> <code>col-xs-*</code> class...</p>
<pre><code><div class="container">
<div class="row">
<div class="col-xs-4">.col-4</div>
<div class="col-xs-4">.col-4</div>
<div class="col-xs-4">.col-4</div>
</div>
</div>
</code></pre>
<p>Demo: <a href="http://bootply.com/80085" rel="noreferrer">http://bootply.com/80085</a></p>
<p><strong><em>EDIT:</em></strong> <strong>Bootstrap 4</strong>, the <code>xs</code> no longer needs to be specified..</p>
<pre><code><div class="container-fluid">
<div class="row">
<div class="col-4">.col-4</div>
<div class="col-4">.col-4</div>
<div class="col-4">.col-4</div>
</div>
</div>
</code></pre> |
23,788,564 | npm add root CA | <p>I am looking for a way to add a custom CA to NPM so I can download from a location using said certificate (an internal git-server) without having to nuke all CA-checking with</p>
<pre><code>npm config set strict-ssl false
</code></pre>
<p>Is there any way of achieving this or not? (if not: is there already a defect?)</p> | 27,997,570 | 2 | 0 | null | 2014-05-21 16:10:28.273 UTC | 30 | 2022-09-07 00:05:29.55 UTC | 2018-03-23 11:54:10.197 UTC | null | 907,512 | null | 907,512 | null | 1 | 85 | npm|ca | 104,516 | <p>You can point npm to a <a href="https://docs.npmjs.com/using-npm/config#cafile" rel="nofollow noreferrer"><code>cafile</code></a></p>
<pre><code>npm config set cafile /path/to/cert.pem
</code></pre>
<p>You can also configure <a href="https://docs.npmjs.com/using-npm/config#ca" rel="nofollow noreferrer"><code>ca</code></a> string(s) directly.</p>
<pre><code>npm config set ca "cert string"
</code></pre>
<p><a href="https://docs.npmjs.com/using-npm/config#ca" rel="nofollow noreferrer"><code>ca</code></a> can be an array of cert strings too. In your <code>.npmrc</code>:</p>
<pre><code>ca[]="cert 1 base64 string"
ca[]="cert 2 base64 string"
</code></pre>
<p>The <code>npm config</code> commands above will persist the relevant config items to your <code>~/.npmrc</code> file:</p>
<pre><code>cafile=/path/to/cert.pem
</code></pre>
<p><strong><em>Note</em></strong>: these CA settings will override the default "real world" certificate authority lookups that npm uses. If you try and use any public npm registries via https that aren't signed by your CA certificate, you will get errors.</p>
<p>So, if you need to support both public https npm registries as well as your own, you could use <a href="https://curl.haxx.se/docs/caextract.html" rel="nofollow noreferrer">curl's Mozilla based CA bundle</a> and append your CA cert to the <code>cacert.pem</code> file:</p>
<pre><code>curl -o ~/.npm.certs.pem https://curl.se/ca/cacert.pem
cat my-ca-cert.pem >> ~/.npm.certs.pem
npm config set cafile ~/.npm.certs.pem
</code></pre>
<p>Unfortunately npm's CA bundle is not editable as it's provided in the <a href="https://github.com/nodejs/node/blob/master/src/node_root_certs.h" rel="nofollow noreferrer">source code</a> (thanks <a href="https://stackoverflow.com/users/2816199/tomekwi">tomekwi</a>) but <a href="https://stackoverflow.com/a/56239954/1318694">nitzel has provided a generic Node.js method</a> to append a certificate via the <code>NODE_EXTRA_CA_CERTS</code> environment variable.</p>
<p><strong><em>RHEL Note</em></strong>: If you happen to be using a RHEL based distro and the RHEL packaged nodejs/npm you can use the standard <a href="https://stackoverflow.com/a/45000022/1318694"><code>update-ca-trust</code> method</a> as RedHat points their packages at the system CA's.</p> |
23,885,436 | #2002 - The server is not responding (or the local MySQL server's socket is not correctly configured) | <p>I can't access to PHPMyAdmin. when i want to go there, i got this error:</p>
<blockquote>
<p>#2002 - The server is not responding (or the local MySQL server's socket is not correctly configured)</p>
</blockquote>
<p>I googled this error but it don't clear.</p>
<p>I try to know that which port is open by this code :</p>
<pre><code>pgrep mysql
</code></pre>
<p>two ports are open when mysql is running.</p>
<p>I want to access to PHPMyAdmin in my localhost. I am using Ubuntu OS</p> | 23,887,210 | 4 | 0 | null | 2014-05-27 09:14:43.503 UTC | 3 | 2018-08-30 11:15:09.69 UTC | 2014-05-27 10:50:52.71 UTC | null | 2,264,626 | null | 2,646,182 | null | 1 | 5 | php|mysql|sockets|phpmyadmin|xampp | 55,402 | <p>In Ubuntu, by default <code>mysql</code> is not listening to TCP/IP connections. It just uses a local socket.</p>
<p>The current local socket is configured in <code>/etc/mysql/my.cnf</code> . If you open this file, you should find something similar to:</p>
<pre><code>[client]
port = 3306
socket = /var/run/mysqld/mysqld.sock
</code></pre>
<p>What you should do is just to open <code>PHPMyAdmin</code>'s config file (<code>config.inc.php</code>) and change the socket address. Maybe there's no local socket configuration on your PHPMyAdmin, or maybe it is different. This file should contain a line like (of course, adapt the address to what you found on <code>my.cnf</code>):</p>
<pre><code>$cfg['Servers'][$i]['socket'] = '/var/run/mysqld/mysqld.sock';
</code></pre> |
43,178,668 | record the computation time for each epoch in Keras during model.fit() | <p>I want to compare the computation time between different models.
During the fit the computation time per epoch is printed to the console.</p>
<pre><code>Epoch 5/5
160000/160000 [==============================] - **10s** ......
</code></pre>
<p>I'm looking for a way to store these times in a similar way to the model metrics that are saved in each epoch and avaliable through the history object.</p> | 43,186,440 | 3 | 0 | null | 2017-04-03 07:16:34.993 UTC | 11 | 2020-07-25 08:33:15.92 UTC | 2017-07-12 21:00:30.153 UTC | null | 5,974,433 | null | 6,293,886 | null | 1 | 32 | python|machine-learning|neural-network|deep-learning|keras | 19,979 | <p>Try the following callback:</p>
<pre><code>class TimeHistory(keras.callbacks.Callback):
def on_train_begin(self, logs={}):
self.times = []
def on_epoch_begin(self, batch, logs={}):
self.epoch_time_start = time.time()
def on_epoch_end(self, batch, logs={}):
self.times.append(time.time() - self.epoch_time_start)
</code></pre>
<p>Then:</p>
<pre><code>time_callback = TimeHistory()
model.fit(..., callbacks=[..., time_callback],...)
times = time_callback.times
</code></pre>
<p>In this case <code>times</code> should store the epoch computation times.</p> |
43,235,863 | Get value from selected dropdown list in Angular 2 | <p>I have a database table with two attributes (Name_of_Game and Type_of_Game). I have been to extract the <strong>Name_of_Game</strong> into a select dropdown list. But this is what i want to do now. After selecting the game from the dropdown list, how can the <strong>type</strong> input be set to the game's respective type automatically? </p>
<p><strong>Example</strong></p>
<p>Game<br>
Lord of the Rings</p>
<p>Type</p>
<p>Adventure </p>
<p>After selecting Lord of the rings from the dropdown list, the type input box should be automatically set to Adventure.</p>
<pre><code> //Component
export class ChatComponent{
Game : Games [];
constructor(private http:HttpService){
// list all games into the dropdown list
this.http.listgames()
.subscribe(data => {
this.Games = data;
})
}
//html
<div class="form-group">
<select class="form-control" name="game" [(ngModel)]="game.name" required>
<option *ngFor="let games of Games" [ngValue]="games" > {{games.name}} </option>
</select>
</div>
<div class="form-group">
<label for="type">Type:</label>
<input type="type" class="form-control" name="type" [(ngModel)]="game.type">
</div>
</code></pre> | 43,248,649 | 3 | 0 | null | 2017-04-05 15:43:43.347 UTC | 4 | 2017-12-20 10:17:16.653 UTC | 2017-04-05 15:59:04.547 UTC | null | 3,858,469 | null | 7,441,935 | null | 1 | 4 | angular | 46,357 | <p>Please look at the naming convention, I have changed names in my example a bit, to more reflect the lower/uppercase we usually use ;)</p>
<p>You are on the right track for using <code>[ngValue]</code>. Have your name bind the whole object, which we can then use in the type, to show the corresponding type. So let's create a variable to which we will store the chosen game when user chooses a name from the drop down list here let's call it <code>selectedGame</code>:</p>
<p>Component:</p>
<pre class="lang-html prettyprint-override"><code>selectedGame: Object = {};
</code></pre>
<p>Template:</p>
<pre class="lang-html prettyprint-override"><code><select [(ngModel)]="selectedGame" required>
<option *ngFor="let game of games" [ngValue]="game">{{game.name}}</option>
</select>
</code></pre>
<p>Now we have bound the whole object to <code>selectedGame</code>, so the input field will reflect that we make a change, as we use <code>selectedGame.type</code> as two way-binding for the input field. So your template would look like this:</p>
<pre class="lang-html prettyprint-override"><code><label>Name:</label>
<select [(ngModel)]="selectedGame" required>
<option *ngFor="let game of games" [ngValue]="game" > {{game.name}} </option>
</select>
<label>Type:</label>
<input type="type"name="type" [(ngModel)]="selectedGame.type">
</code></pre>
<p>Here's a </p>
<h2><a href="http://plnkr.co/edit/LdkniAYmu1ADKPXdQK2J?p=preview" rel="noreferrer">Demo</a></h2> |
2,339,776 | Mixing VB.Net and C# Code in an ASP.Net Web Site project? | <p>The question quite an older and often asked around, i have similar questions here but my question is a bit more specific.</p>
<p>Q1. Is it legal to mix C# and VB.Net code in ASP.Net Web site? Will it work or not? If it works how it may be done? Any sample will be good.</p>
<p>Q2. If there are any repercussions of mixing C# and VB.Net code then please do share those as well.</p>
<p>I have a web project that is coded in VB.Net. I am working on one module of the project. and i want to code in C#. I cant convert the whole project to C# because i am not the only one working on the project. However, the module i intend to build , i want to have that built in C#. </p>
<p>I have heard that in case of web projects, if we code part in C# and part in VB.net then there are problems compiling the project to a dll. Is that true? if yes then what is the solution. </p>
<p>Also, if i am building a dynamic link library in .Net then can i mix C# and Vb.Net code?</p> | 2,339,827 | 3 | 0 | null | 2010-02-26 06:00:30.107 UTC | 20 | 2013-07-08 17:56:53.083 UTC | 2013-07-08 17:56:53.083 UTC | null | 299,327 | null | 248,700 | null | 1 | 25 | c#|asp.net|vb.net|web-site-project | 22,275 | <p>From <a href="http://msdn.microsoft.com/en-us/library/t990ks23.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/t990ks23.aspx</a>:</p>
<p><strong>Multiple Programming Languages in the App_Code Folder</strong></p>
<p>Because the source code in the App_Code folder is compiled into a single assembly, all the files in the App_Code folder must be in the same programming language. For example, the App_Code folder cannot include source code in both Visual Basic and C#. </p>
<p>However, you can configure your Web application to treat subfolders of the App_Code folder as separate compilable units. Each folder can then contain source code in a different programming language. The configuration is specified by creating a codeSubDirectories element in the compilation element of the Web.config file and adding a reference to the subfolder. The following example illustrates how you would configure subfolders named VBCode and CSCode to compile into separate assemblies:</p>
<pre><code><compilation debug="false">
<codeSubDirectories>
<add directoryName="VBCode" />
<add directoryName="CSCode" />
</codeSubDirectories>
</compilation>
</code></pre>
<p>The references to the VBCode and CSCode subfolders do not need to include any information about what programming language is contained in the subfolder. As with the App_Code folder itself, ASP.NET infers the compiler to use based on the files in the subfolder.</p> |
3,030,585 | Where is the Google App Engine SDK path on OSX? | <p>I need to know for creating a Pydev Google App Engine Project in Eclipse.</p> | 3,030,645 | 3 | 0 | null | 2010-06-13 00:14:37.123 UTC | 11 | 2018-06-28 14:45:55.253 UTC | null | null | null | null | 41,742 | null | 1 | 31 | python|eclipse|google-app-engine|pydev | 17,853 | <p><code>/usr/local/google_appengine</code> - that's a symlink that links to the SDK.</p> |
50,228,138 | Can't bind to 'dataSource' since it isn't a known property of 'table' | <p>I am new in angular 5 development. I am trying to develop a data table with angular material using the example provided here: "<a href="https://material.angular.io/components/table/examples" rel="noreferrer">https://material.angular.io/components/table/examples</a>".</p>
<p>I am getting an error saying <code>Can't bind to 'dataSource' since it isn't a known property of 'table'.</code></p>
<p><a href="https://i.stack.imgur.com/7PQMu.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/7PQMu.jpg" alt="enter image description here"></a></p>
<p>Please help.</p> | 50,230,116 | 18 | 11 | null | 2018-05-08 07:26:35.883 UTC | 14 | 2022-09-01 16:37:57.853 UTC | 2018-05-08 07:33:54.437 UTC | null | 5,394,220 | null | 2,118,422 | null | 1 | 138 | angular|datatable|angular-material | 193,570 | <p>Thanx to @Jota.Toledo, I got the solution for my table creation.
Please find the working code below:</p>
<p><strong><em>component.html</em></strong></p>
<pre class="lang-html prettyprint-override"><code><mat-table #table [dataSource]="dataSource" matSort>
<ng-container matColumnDef="{{column.id}}" *ngFor="let column of columnNames">
<mat-header-cell *matHeaderCellDef mat-sort-header> {{column.value}}</mat-header-cell>
<mat-cell *matCellDef="let element"> {{element[column.id]}}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
</code></pre>
<p><strong><em>component.ts</em></strong></p>
<pre class="lang-js prettyprint-override"><code>import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource, MatSort } from '@angular/material';
import { DataSource } from '@angular/cdk/table';
@Component({
selector: 'app-m',
templateUrl: './m.component.html',
styleUrls: ['./m.component.css'],
})
export class MComponent implements OnInit {
dataSource;
displayedColumns = [];
@ViewChild(MatSort) sort: MatSort;
/**
* Pre-defined columns list for user table
*/
columnNames = [{
id: 'position',
value: 'No.',
}, {
id: 'name',
value: 'Name',
},
{
id: 'weight',
value: 'Weight',
},
{
id: 'symbol',
value: 'Symbol',
}];
ngOnInit() {
this.displayedColumns = this.columnNames.map(x => x.id);
this.createTable();
}
createTable() {
let tableArr: Element[] = [{ position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
{ position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
{ position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' },
{ position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' },
{ position: 5, name: 'Boron', weight: 10.811, symbol: 'B' },
{ position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C' },
];
this.dataSource = new MatTableDataSource(tableArr);
this.dataSource.sort = this.sort;
}
}
export interface Element {
position: number,
name: string,
weight: number,
symbol: string
}
</code></pre>
<p><strong><em>app.module.ts</em></strong></p>
<pre class="lang-js prettyprint-override"><code>imports: [
MatSortModule,
MatTableModule,
],
</code></pre> |
37,686,841 | Find Column Header By Name And Select All Data Below Column Header (Excel-VBA) | <p>I'm attempting to create a macro to do the following:</p>
<ol>
<li>Search a spreadsheet column header by name.</li>
<li>Select all data from the selected column, except column header.</li>
<li>Take Number Stored As Text & Convert to Number.</li>
</ol>
<ul>
<li>Converting to Number to use for VLookup.</li>
</ul>
<p>For Example:</p>
<p>Visual Spreadsheet Example:</p>
<p><a href="https://i.stack.imgur.com/NaGXV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NaGXV.png" alt="enter image description here" /></a></p>
<p>I've discovered the following code online:</p>
<pre><code>With ActiveSheet.UsedRange
Set c = .Find("Employee ID", LookIn:=xlValues)
If Not c Is Nothing Then
ActiveSheet.Range(c.Address).Offset(1, 0).Select
End If
End With
</code></pre>
<p>However, I'm still experiencing some issues.</p> | 37,687,346 | 5 | 0 | null | 2016-06-07 18:36:04.82 UTC | 5 | 2021-06-07 15:14:46.433 UTC | 2021-06-07 15:14:46.433 UTC | null | 648,265 | null | 6,436,768 | null | 1 | 8 | vba|excel | 117,197 | <p>Try this out. Simply add all the column header names you want to find into the collection. I'm assuming you don't have more than 200 columns, if you do simply update the for i = 1 to 200 section to a larger number.</p>
<pre><code>Public Sub FindAndConvert()
Dim i As Integer
Dim lastRow As Long
Dim myRng As Range
Dim mycell As Range
Dim MyColl As Collection
Dim myIterator As Variant
Set MyColl = New Collection
MyColl.Add "Some Value"
MyColl.Add "Another Value"
lastRow = ActiveSheet.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
For i = 1 To 200
For Each myIterator In MyColl
If Cells(1, i) = myIterator Then
Set myRng = Range(Cells(2, i), Cells(lastRow, i))
For Each mycell In myRng
mycell.Value = Val(mycell.Value)
Next
End If
Next
Next
End Sub
</code></pre> |
46,622,869 | Pandas: groupby column A and make lists of tuples from other columns? | <p>I would like to aggregate user transactions into lists in pandas. I can't figure out how to make a list comprised of more than one field. For example,</p>
<pre><code>df = pd.DataFrame({'user':[1,1,2,2,3],
'time':[20,10,11,18, 15],
'amount':[10.99, 4.99, 2.99, 1.99, 10.99]})
</code></pre>
<p>which looks like</p>
<pre><code> amount time user
0 10.99 20 1
1 4.99 10 1
2 2.99 11 2
3 1.99 18 2
4 10.99 15 3
</code></pre>
<p>If I do</p>
<pre><code>print(df.groupby('user')['time'].apply(list))
</code></pre>
<p>I get </p>
<pre><code>user
1 [20, 10]
2 [11, 18]
3 [15]
</code></pre>
<p>but if I do</p>
<pre><code>df.groupby('user')[['time', 'amount']].apply(list)
</code></pre>
<p>I get</p>
<pre><code>user
1 [time, amount]
2 [time, amount]
3 [time, amount]
</code></pre>
<p>Thanks to an answer below, I learned I can do this</p>
<pre><code>df.groupby('user').agg(lambda x: x.tolist()))
</code></pre>
<p>to get</p>
<pre><code> amount time
user
1 [10.99, 4.99] [20, 10]
2 [2.99, 1.99] [11, 18]
3 [10.99] [15]
</code></pre>
<p>but I'm going to want to sort time and amounts in the same order - so I can go through each users transactions in order. </p>
<p>I was looking for a way to produce this:</p>
<pre><code> amount-time-tuple
user
1 [(20, 10.99), (10, 4.99)]
2 [(11, 2.99), (18, 1.99)]
3 [(15, 10.99)]
</code></pre>
<p>but maybe there is a way to do the sort without "tupling" the two columns?</p> | 46,623,290 | 4 | 1 | null | 2017-10-07 17:02:56.1 UTC | 8 | 2021-03-03 12:41:20.29 UTC | 2017-10-07 18:00:37.863 UTC | null | 2,280,020 | null | 2,280,020 | null | 1 | 24 | python|pandas|dataframe|pandas-groupby | 15,363 | <p><code>apply(list)</code> will consider the series index not the values .I think you are looking for </p>
<pre><code>df.groupby('user')[['time', 'amount']].apply(lambda x: x.values.tolist())
</code></pre>
<pre>
user
1 [[23.0, 2.99], [50.0, 1.99]]
2 [[12.0, 1.99]]
</pre> |
36,588,084 | pyspark mysql jdbc load An error occurred while calling o23.load No suitable driver | <p>I use docker image <a href="https://hub.docker.com/r/sequenceiq/spark/" rel="noreferrer">sequenceiq/spark</a> on my Mac to study these <a href="http://spark.apache.org/examples.html" rel="noreferrer">spark examples</a>, during the study process, I upgrade the spark inside that image to 1.6.1 according to <a href="https://stackoverflow.com/questions/33887227/how-to-upgrade-spark-to-newer-version/33914992#33914992">this answer</a>, and the error occurred when I start the <code>Simple Data Operations</code> example, here is what happened:</p>
<p>when I run <code>df = sqlContext.read.format("jdbc").option("url",url).option("dbtable","people").load()</code> it raise a error, and the full stack with the pyspark console is as followed:</p>
<pre><code>Python 2.6.6 (r266:84292, Jul 23 2015, 15:22:56)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
16/04/12 22:45:28 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Welcome to
____ __
/ __/__ ___ _____/ /__
_\ \/ _ \/ _ `/ __/ '_/
/__ / .__/\_,_/_/ /_/\_\ version 1.6.1
/_/
Using Python version 2.6.6 (r266:84292, Jul 23 2015 15:22:56)
SparkContext available as sc, HiveContext available as sqlContext.
>>> url = "jdbc:mysql://localhost:3306/test?user=root;password=myPassWord"
>>> df = sqlContext.read.format("jdbc").option("url",url).option("dbtable","people").load()
16/04/12 22:46:05 WARN Connection: BoneCP specified but not present in CLASSPATH (or one of dependencies)
16/04/12 22:46:06 WARN Connection: BoneCP specified but not present in CLASSPATH (or one of dependencies)
16/04/12 22:46:11 WARN ObjectStore: Version information not found in metastore. hive.metastore.schema.verification is not enabled so recording the schema version 1.2.0
16/04/12 22:46:11 WARN ObjectStore: Failed to get database default, returning NoSuchObjectException
16/04/12 22:46:16 WARN Connection: BoneCP specified but not present in CLASSPATH (or one of dependencies)
16/04/12 22:46:17 WARN Connection: BoneCP specified but not present in CLASSPATH (or one of dependencies)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/spark/python/pyspark/sql/readwriter.py", line 139, in load
return self._df(self._jreader.load())
File "/usr/local/spark/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py", line 813, in __call__
File "/usr/local/spark/python/pyspark/sql/utils.py", line 45, in deco
return f(*a, **kw)
File "/usr/local/spark/python/lib/py4j-0.9-src.zip/py4j/protocol.py", line 308, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o23.load.
: java.sql.SQLException: No suitable driver
at java.sql.DriverManager.getDriver(DriverManager.java:278)
at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$2.apply(JdbcUtils.scala:50)
at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$2.apply(JdbcUtils.scala:50)
at scala.Option.getOrElse(Option.scala:120)
at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$.createConnectionFactory(JdbcUtils.scala:49)
at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD$.resolveTable(JDBCRDD.scala:120)
at org.apache.spark.sql.execution.datasources.jdbc.JDBCRelation.<init>(JDBCRelation.scala:91)
at org.apache.spark.sql.execution.datasources.jdbc.DefaultSource.createRelation(DefaultSource.scala:57)
at org.apache.spark.sql.execution.datasources.ResolvedDataSource$.apply(ResolvedDataSource.scala:158)
at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:119)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:231)
at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:381)
at py4j.Gateway.invoke(Gateway.java:259)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:209)
at java.lang.Thread.run(Thread.java:744)
>>>
</code></pre>
<p>Here is what I have tried till now:</p>
<ol>
<li><p>Download <code>mysql-connector-java-5.0.8-bin.jar</code>, and put it in to <code>/usr/local/spark/lib/</code>. It still the same error.</p></li>
<li><p>Create <code>t.py</code> like this:</p>
<pre><code>from pyspark import SparkContext
from pyspark.sql import SQLContext
sc = SparkContext(appName="PythonSQL")
sqlContext = SQLContext(sc)
df = sqlContext.read.format("jdbc").option("url",url).option("dbtable","people").load()
df.printSchema()
countsByAge = df.groupBy("age").count()
countsByAge.show()
countsByAge.write.format("json").save("file:///usr/local/mysql/mysql-connector-java-5.0.8/db.json")
</code></pre></li>
</ol>
<p>then, I tried <code>spark-submit --conf spark.executor.extraClassPath=mysql-connector-java-5.0.8-bin.jar --driver-class-path mysql-connector-java-5.0.8-bin.jar --jars mysql-connector-java-5.0.8-bin.jar --master local[4] t.py</code>. The result is still the same.</p>
<ol start="3">
<li>Then I tried <code>pyspark --conf spark.executor.extraClassPath=mysql-connector-java-5.0.8-bin.jar --driver-class-path mysql-connector-java-5.0.8-bin.jar --jars mysql-connector-java-5.0.8-bin.jar --master local[4] t.py</code>, both with and without the following <code>t.py</code>, still the same.</li>
</ol>
<p>During all of this, the mysql is running. And here is my os info:</p>
<pre><code># rpm --query centos-release
centos-release-6-5.el6.centos.11.2.x86_64
</code></pre>
<p>And the hadoop version is 2.6.</p>
<p>Now I don't where to go next, so I hope some one can help give some advice, thanks!</p> | 37,422,017 | 2 | 0 | null | 2016-04-13 03:36:34.55 UTC | 1 | 2021-10-27 14:01:00.137 UTC | 2018-09-26 07:52:40.453 UTC | null | 4,751,173 | null | 1,398,065 | null | 1 | 14 | mysql|jdbc|docker|pyspark|pyspark-sql | 81,106 | <p>I ran into "java.sql.SQLException: No suitable driver" when I tried to have my script write to MySQL.</p>
<p>Here's what I did to fix that.</p>
<p>In script.py</p>
<pre><code>df.write.jdbc(url="jdbc:mysql://localhost:3333/my_database"
"?user=my_user&password=my_password",
table="my_table",
mode="append",
properties={"driver": 'com.mysql.jdbc.Driver'})
</code></pre>
<p>Then I ran spark-submit this way</p>
<pre><code>SPARK_HOME=/usr/local/Cellar/apache-spark/1.6.1/libexec spark-submit --packages mysql:mysql-connector-java:5.1.39 ./script.py
</code></pre>
<p>Note that SPARK_HOME is specific to where spark is installed. For your environment this <a href="https://github.com/sequenceiq/docker-spark/blob/master/README.md" rel="noreferrer">https://github.com/sequenceiq/docker-spark/blob/master/README.md</a> might help.</p>
<p>In case all the above is confusing, try this:<br>
In t.py replace</p>
<pre><code>sqlContext.read.format("jdbc").option("url",url).option("dbtable","people").load()
</code></pre>
<p>with </p>
<pre><code>sqlContext.read.format("jdbc").option("dbtable","people").option("driver", 'com.mysql.jdbc.Driver').load()
</code></pre>
<p>And run that with</p>
<pre><code>spark-submit --packages mysql:mysql-connector-java:5.1.39 --master local[4] t.py
</code></pre> |
52,667,959 | What is the purpose of bivarianceHack in TypeScript types? | <p>While reading through the TypeScript types for React, I saw a few usages of this pattern involving a <code>bivarianceHack()</code> function declaration:</p>
<p><sub><a href="https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L730" rel="noreferrer">@types/react/index.d.ts</a></sub></p>
<pre><code>type EventHandler<E extends SyntheticEvent<any>> = { bivarianceHack(event: E): void }["bivarianceHack"];
</code></pre>
<p>Searching didn't lead me to any documentation on why this particular pattern was used, although I've found <a href="https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/backbone/index.d.ts#L237" rel="noreferrer">other instances</a> of this pattern in use so it seems it's not a React-specific pattern.</p>
<p>Why is this pattern being used rather than <code>(event: E) => void</code>?</p> | 52,668,133 | 1 | 0 | null | 2018-10-05 14:33:42.257 UTC | 9 | 2020-05-19 11:12:51.207 UTC | null | null | null | null | 497,418 | null | 1 | 61 | typescript|types | 5,845 | <p>This has to do with function compatibility under the <code>strictfunctionTypes</code> option. Under this option if the argument is of a derived type you can't pass it to a function that will pass in a base class argument. For example:</p>
<pre><code>class Animal { private x:undefined }
class Dog extends Animal { private d: undefined }
type EventHandler<E extends Animal> = (event: E) => void
let o: EventHandler<Animal> = (o: Dog) => { } // fails under strictFunctionTypes
</code></pre>
<p>There is however a caveat to strict function type, stated in the <a href="https://github.com/Microsoft/TypeScript/pull/18654" rel="noreferrer">PR</a></p>
<blockquote>
<p>The stricter checking applies to all function types, <strong>except those originating in method or constructor declarations</strong>. Methods are excluded specifically to ensure generic classes and interfaces (such as <code>Array<T></code>) continue to mostly relate covariantly. The impact of strictly checking methods would be a much bigger breaking change as a large number of generic types would become invariant (even so, we may continue to explore this stricter mode).</p>
</blockquote>
<p><em>Emphasis added</em></p>
<p>So the role of the hack is to allow the bivariant behavior of <code>EventHandler</code> even under <code>strictFunctionTypes</code>. Since the signature of the event handler will have its source in a method declaration it will not be subject to the stricter function checks.</p>
<pre><code>type BivariantEventHandler<E extends Animal> = { bivarianceHack(event: E): void }["bivarianceHack"];
let o2: BivariantEventHandler<Animal> = (o: Dog) => { } // still ok under strictFunctionTypes
</code></pre>
<p><a href="https://www.typescriptlang.org/play/#src=class%20Animal%20%7B%20private%20x%3Aundefined%20%7D%0D%0Aclass%20Dog%20extends%20Animal%20%7B%20private%20d%3A%20undefined%20%7D%0D%0A%0D%0Atype%20BivariantEventHandler%3CE%20extends%20Animal%3E%20%3D%20%7B%20bivarianceHack(event%3A%20E)%3A%20void%20%7D%5B%22bivarianceHack%22%5D%3B%0D%0Atype%20EventHandler%3CE%20extends%20Animal%3E%20%3D%20(event%3A%20E)%20%3D%3E%20void%0D%0A%0D%0Alet%20o%3A%20EventHandler%3CAnimal%3E%20%3D%20(o%3A%20Dog)%20%3D%3E%20%7B%20%7D%20%2F%2F%20fails%20under%20strictFunctionTypes%0D%0Alet%20o2%3A%20BivariantEventHandler%3CAnimal%3E%20%3D%20(o%3A%20Dog)%20%3D%3E%20%7B%20%7D%20%2F%2F%20still%20ok%20%20under%20strictFunctionTypes%20" rel="noreferrer">Playground link</a></p> |
655,986 | How do manage your Perl application development, build, and deployment? | <p>I have yet to come up with a satisfactory way to manage the development, build, and deployment of my Perl applications. I'd like to hear how you have solved this problem and/or what you would like to have in an application build system that you don't have now.</p>
<p>Please describe your application type (is it a web app, does it run on a server, or do you bundle it using PAR or PerlApp so that you can run on perlless systems).</p>
<p>Key things a build system should provide:</p>
<ul>
<li>Control of libraries.
<ul>
<li>It should be possible to check a library distribution out into my dev directory to use it in my build.</li>
<li>It should be easy to execute perl with an <code>@INC</code> value that will use the appropriate directories.</li>
<li>It should be possible to get a list of modules that are being sourced from the system perl install.</li>
</ul></li>
<li>Makefile/Build integration
<ul>
<li>It should be easy to do a global test across the entire application by issuing only one <code>make test</code> or similar command.</li>
</ul></li>
<li>Version control friendly
<ul>
<li>structure should not interfere with normal usage of CVS, SVN and other version
control systems.</li>
</ul></li>
<li>Cross platform
<ul>
<li>System should operate on Win32 and Unix derived systems at minimum.</li>
<li>Ideally, tools should function identically in all places where perl operates.</li>
</ul></li>
<li>Single Perl install
<ul>
<li>It should not be necessary to install perl into a special directory as part of setting up the environment.</li>
</ul></li>
<li>Easy start up
<ul>
<li>Starting an application should be a mostly automated process. Something along the lines of Module::Starter or h2xs should be available to layout a basic structure and create any standard files. </li>
</ul></li>
</ul>
<p><strong>Cross-posted at <a href="http://perlmonks.org/?node_id=751283" rel="noreferrer">Perlmonks</a>.</strong> </p> | 659,890 | 2 | 0 | null | 2009-03-17 20:53:05.6 UTC | 31 | 2011-08-10 11:18:44.837 UTC | 2009-03-18 01:42:04.25 UTC | null | 59,135 | null | 59,135 | null | 1 | 46 | perl | 3,251 | <p>There's a lot that I could write about this</p>
<ol>
<li><p>Control of libraries - I create my own versions of CPAN with just the modules I want. The latest versions of <a href="http://search.cpan.org/dist/App-Cpan" rel="noreferrer">App::Cpan</a> has several features, such as the <code>-j</code> option to load one-time configurations, to help with this. Once you have this, you can distribute it on a thumb-drive or CD which has all of the modules, the CPAN.pm configuration, and everything else you need. With a little programming you create a <code>run_me</code> script that make it all happen.</p></li>
<li><p>Makefile/Build integration - I don't integrate the Makefiles. That's the road to disaster. Instead, I do integration testing with the top-level application module, which automatically tests all of its dependencies too. The <code>-t</code> switch to the cpan command is useful to test the module in the current working directory:</p>
<p>cpan -t .</p></li>
</ol>
<p>There are various intergation testing frameworks that you can use too. You set PERL5LIB to something empty (with only have the core modules in the hard-coded @INC directories) so <code>cpan</code> has to install everything from scratch.</p>
<ol start="3">
<li><p>Version control friendly - it doesn't much matter what you use. Most things have some sort of export where you can get everything without the source control stuff. Git is very nice because it only has a minimum of pollution in the normal cases.</p></li>
<li><p>Cross platform - everything I've mentioned works just fine on Windows and Unix.</p></li>
<li><p>Single Perl install - this part is more tricky, and I think you're going in the wrong way. Any time multiple things have to depend on the same perl, someone is going to mess it up for the others. I definitely recommend not using the system Perl for application development just so you don't mess up the operation of the system. At the minimum, every application should install all non-core modules into their own directories so they don't compete with other applications.</p></li>
<li><p>Easy start up - that's just a simple matter of programming.</p></li>
</ol>
<p>BONUS: I don't use Module::Starter. It's the wrong way to go since you have to depend what Module::Starter thinks you should do. I use <a href="http://search.cpan.org/dist/Distribution-Cooker" rel="noreferrer">Distribution::Cooker</a> which simply takes a directory of Template Toolkit templates and processes them to give them your distribution directory. You can do anything that you like. How you get the initial templates is up to you.</p> |
2,562,986 | getDate with Jquery Datepicker | <p>i am trying to get date from my implementation of jquery date picker, add it to a string and display the resulting image in my div. Something however is just not working. Can anyone check out the code and have a look at it? </p>
<p>The code is supposed to take the date from date picker, combine it in a string which is to have the necessary code to display tag, images are located in /image and in the format aYY-MM-DD.png, new to this date picker and can't quite get it down yet.</p>
<pre><code><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link type="text/css" href="css/ui-lightness/jquery-ui-1.8.custom.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.custom.min.js"></script>
<script type="text/javascript">
$(function(){
// Datepicker
$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd',
inline: true,
minDate: new Date(2010, 1 - 1, 1),
maxDate:new Date(2010, 12 - 1, 31),
altField: '#datepicker_value',
});
//hover states on the static widgets
$('#dialog_link, ul#icons li').hover(
function() { $(this).addClass('ui-state-hover'); },
function() { $(this).removeClass('ui-state-hover'); }
);
});
//var img_date = .datepicker('getDate');
var day1 = $("#datepicker").datepicker('getDate').getDate();
var month1 = $("#datepicker").datepicker('getDate').getMonth() + 1;
var year1 = $("#datepicker").datepicker('getDate').getFullYear();
var fullDate = year1 + "-" + month1 + "-" + day1;
var str_output = "<h1><center><img src=\"/images/a" + fullDate + ".png\"></center></h1><br/><br>";
page_output.innerHTML = str_output;
// writing the results to the div element (page_out)
</script>
</head>
<body style="background-color:#000;color:#fff;margin: auto auto;">
<!-- Datepicker -->
<div id="datepicker"></div>
<!-- Highlight / Error -->
<p>Date Value: <input type="text" id="datepicker_value" /></p>
<div id="page_output" style="text-align:center; margin-top:80px; margin-bottom:20px; "></div>
</body>
</code></pre>
<p></p> | 2,563,319 | 5 | 0 | null | 2010-04-01 19:14:36.823 UTC | 7 | 2017-04-05 12:47:15.38 UTC | null | null | null | null | 301,760 | null | 1 | 18 | jquery|datepicker|uidatepicker|jquery-ui-datepicker | 112,767 | <p>I think you would want to add an 'onSelect' event handler to the initialization of your datepicker so your code gets triggered when the user selects a date. Try it out on <a href="http://jsfiddle.net/KsKCW/" rel="noreferrer">jsFiddle</a></p>
<pre><code>$(document).ready(function(){
// Datepicker
$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd',
inline: true,
minDate: new Date(2010, 1 - 1, 1),
maxDate:new Date(2010, 12 - 1, 31),
altField: '#datepicker_value',
onSelect: function(){
var day1 = $("#datepicker").datepicker('getDate').getDate();
var month1 = $("#datepicker").datepicker('getDate').getMonth() + 1;
var year1 = $("#datepicker").datepicker('getDate').getFullYear();
var fullDate = year1 + "-" + month1 + "-" + day1;
var str_output = "<h1><center><img src=\"/images/a" + fullDate +".png\"></center></h1><br/><br>";
$('#page_output').html(str_output);
}
});
});
</code></pre> |
3,027,561 | Delphi - how to get a list of all files of directory | <p>I am working with delphi, I want a list of all files of a directory when I execute openpicturedialog. </p>
<blockquote>
<p>i.e., When open dialog is executed and
i select one file from it, I want the
list of all files from the directory
of selected file.</p>
</blockquote>
<p>You can even suggest me for getting directory name from <code>FileName</code> property of <code>TOpenDialog</code><br>
Thank You. </p> | 3,027,657 | 6 | 0 | null | 2010-06-12 05:06:05.383 UTC | 3 | 2021-12-24 21:02:29.297 UTC | 2013-06-21 11:33:06.927 UTC | null | 368,364 | null | 327,522 | null | 1 | 25 | delphi|opendialog | 84,056 | <p>@Himadri, the primary objective of the OpenPictureDialog is not select an directory, anyway if you are using this dialog with another purpose you can try this code.</p>
<pre><code>Var
Path : String;
SR : TSearchRec;
DirList : TStrings;
begin
if OpenPictureDialog1.Execute then
begin
Path:=ExtractFileDir(OpenPictureDialog1.FileName); //Get the path of the selected file
DirList:=TStringList.Create;
try
if FindFirst(Path + '*.*', faArchive, SR) = 0 then
begin
repeat
DirList.Add(SR.Name); //Fill the list
until FindNext(SR) <> 0;
FindClose(SR);
end;
//do your stuff
finally
DirList.Free;
end;
end;
end;
</code></pre> |
2,665,532 | Is there a good R API for accessing Google Docs? | <p>I'm using R for data analysis, and I'm sharing some data with collaborators via Google docs. Is there a simple interface that I can use to access a R data.frame object to and from a Google Docs spreadsheet? If not, is there a similar API in other languages? </p> | 2,665,698 | 6 | 0 | null | 2010-04-19 06:30:19.877 UTC | 10 | 2017-03-28 15:21:44.413 UTC | null | null | null | null | 57,458 | null | 1 | 27 | r|statistics|google-docs | 5,469 | <p>There are two packages:</p>
<ul>
<li><a href="http://www.omegahat.net/RGoogleDocs/" rel="nofollow noreferrer">RGoogleDocs</a> on Omegahat: the package allows you to get a list of the documents and details about each of them, download the contents of a document, remove a document, and upload a document, even binary files. </li>
<li><a href="http://r-forge.r-project.org/projects/rgoogledata/" rel="nofollow noreferrer">RGoogleData</a> on RForge: provides R access to Google services through the Google supported Java API. Currently the R interface only supports Google Docs and Spreadsheets.</li>
</ul> |
2,572,158 | What is AOP, Dependency Injection and Inversion Of Control in Simple English | <p>I have tried to understand AOP, Dependency Injection and Inversion of Control SPRING related concepts but I am having hard time understanding it. </p>
<p>Can anyone explain this in simple English ?</p> | 2,575,156 | 6 | 0 | null | 2010-04-03 18:03:08.573 UTC | 30 | 2016-03-05 21:29:21.15 UTC | 2012-09-21 13:29:05.723 UTC | null | 7,028 | null | 164,299 | null | 1 | 37 | java|spring|dependency-injection|inversion-of-control|aop | 25,106 | <p>I understand your confusion and it took me some time to understand how these concepts were related together. So here is my (somehow personal) explanation of all this:</p>
<p><strong>1. Inversion of Control</strong></p>
<p><a href="http://martinfowler.com/bliki/InversionOfControl.html" rel="noreferrer">Inversion of control</a> is a design principle rather generic that refers to the decoupling of the specification of a behavior from when it is actually executed. Compare for instance,</p>
<pre><code>myDependency.doThis();
</code></pre>
<p>with</p>
<pre><code>myDependency.onEventX += doThis();
</code></pre>
<p>In the latter, there is <em>no direct invocation</em> which is more flexible. In its general form, inversion of control relates to the <em>observer pattern</em>, <em>events</em>, or <em>callbacks</em>. </p>
<p><strong>2. Dependency inversion</strong></p>
<p>Dependency inversion is another design principle. Roughly speaking, it says that higher-level abstraction should not depend directly on lower-level abstractions; this results indeed in a design where higher-level abstraction can not be reused without the lower-level abstractions. </p>
<pre><code> class MyHighLevelClass {
MyLowLevelClass dep = new MyLowLeverClass();
}
class App {
void main() { new HighLevelClass().doStuff(); }
}
</code></pre>
<p>Here, <code>MyHighLevelClass</code> can not compile without access to <code>MyLowLevelClass</code>. To break this coupling, we need to <em>abstract</em> the low level class with an interface, and remove the direct instantiation. </p>
<pre><code>class MyLowLevelClass implements MyUsefulAbstraction { ... }
class MyHighLevelClass {
MyUsefulAbstraction dep;
MyHighLevelClass( MyUsefulAbstraction dep ) {
this.dep = dep;
}
}
class App {
void main() { new HighLevelClass( new LowLevelClass() ).doStuff(); }
}
</code></pre>
<p>Note that you don't need anything special like a container to enforce dependency inversion, which is a principle. A good reading is <a href="https://drive.google.com/a/cleancoder.com/file/d/0BwhCYaYDn8EgMjdlMWIzNGUtZTQ0NC00ZjQ5LTkwYzQtZjRhMDRlNTQ3ZGMz" rel="noreferrer">The Dependency Inversion Principle</a> by Uncle Bob.</p>
<p><strong>3. Dependency injection</strong></p>
<p>Now comes dependency injection. To me <code>dependency injection = IoC + dependency inversion</code>: </p>
<ol>
<li>dependencies are provided externally so we enforce the dependency inversion principle</li>
<li>the container sets the dependencies (not us) so we speak of inversion of control</li>
</ol>
<p>In the example I provided above, dependency injection can be done if a container is used to instantiate objects and automatically <em>inject</em> the dependency in the constructor (we speak then frequently of DI container):</p>
<pre><code> class App {
void main() { DI.getHighLevelObject().doStuff(); }
}
</code></pre>
<p>Note that there are various <a href="http://martinfowler.com/articles/injection.html#FormsOfDependencyInjection" rel="noreferrer">form of injections</a>. Note also that under this perspective, <a href="http://martinfowler.com/articles/injection.html#SetterInjectionWithSpring" rel="noreferrer">setter injection</a> can be seen as a form of callback -- the DI container creates the object then calls back the setter. The flow of control is effectively inverted.</p>
<p><strong>4. AOP</strong></p>
<p>Strictly speaking, AOP has little to do with the 3 previous points. The <a href="http://www.cs.ubc.ca/~gregor/papers/kiczales-ECOOP1997-AOP.pdf" rel="noreferrer">seminal paper on AOP</a> is very generic and present the idea of weaving various sources together (possibly expressed with different languages) to produce a working software. </p>
<p>I won't expand more on AOP. What is important here, is that dependency injection and AOP do effectively plays nicely together because it makes the weaving very easy. If an IoC container and dependency injection is used to abstract away the instantiation of objects, the IoC container can easily be used to weave the aspects before injecting the dependencies. This would otherwise requires a special compilation or a special <code>ClassLoader</code>. </p>
<p>Hope this helps.</p> |
2,588,628 | What is the purpose of subclassing the class "object" in Python? | <p>All the Python built-ins are subclasses of <code>object</code> and I come across many user-defined classes which are too. Why? What is the purpose of the class <code>object</code>? It's just an empty class, right?</p> | 2,588,667 | 6 | 0 | null | 2010-04-06 21:54:50.137 UTC | 8 | 2012-08-12 23:02:47.803 UTC | 2012-08-12 23:02:47.803 UTC | null | 202,229 | ignoramus | null | null | 1 | 64 | python|object|deprecated|future-proof|new-style-class | 18,700 | <p>In short, it sets free magical ponies.</p>
<p>In long, Python 2.2 and earlier used "old style classes". They were a particular implementation of classes, and they had a few limitations (for example, you couldn't subclass builtin types). The fix for this was to create a new style of class. But, doing this would involve some backwards-incompatible changes. So, to make sure that code which is written for old style classes will still work, the <code>object</code> class was created to act as a superclass for all new-style classes.
So, in Python 2.X, <code>class Foo: pass</code> will create an old-style class and <code>class Foo(object): pass</code> will create a new style class.</p>
<p>In longer, see Guido's <a href="http://www.python.org/download/releases/2.2.3/descrintro/" rel="noreferrer"><em>Unifying types and classes in Python 2.2</em></a>.</p>
<p>And, in general, it's a good idea to get into the habit of making all your classes new-style, because some things (the <code>@property</code> decorator is one that comes to mind) won't work with old-style classes.</p> |
2,702,545 | Workaround for the WaitHandle.WaitAll 64 handle limit? | <p>My application spawns loads of different small worker threads via <code>ThreadPool.QueueUserWorkItem</code> which I keep track of via multiple <code>ManualResetEvent</code> instances. I use the <code>WaitHandle.WaitAll</code> method to block my application from closing until these threads have completed.</p>
<p>I have never had any issues before, however, as my application is coming under more load i.e. more threads being created, I am now beginning to get this exception:</p>
<p><code>WaitHandles must be less than or equal to 64 - missing documentation</code></p>
<p>What is the best alternative solution to this?</p>
<p><b> Code Snippet </b></p>
<pre><code>List<AutoResetEvent> events = new List<AutoResetEvent>();
// multiple instances of...
var evt = new AutoResetEvent(false);
events.Add(evt);
ThreadPool.QueueUserWorkItem(delegate
{
// do work
evt.Set();
});
...
WaitHandle.WaitAll(events.ToArray());
</code></pre>
<p><b> Workaround </b></p>
<pre><code>int threadCount = 0;
ManualResetEvent finished = new ManualResetEvent(false);
...
Interlocked.Increment(ref threadCount);
ThreadPool.QueueUserWorkItem(delegate
{
try
{
// do work
}
finally
{
if (Interlocked.Decrement(ref threadCount) == 0)
{
finished.Set();
}
}
});
...
finished.WaitOne();
</code></pre> | 2,702,562 | 8 | 1 | null | 2010-04-23 23:31:53.32 UTC | 22 | 2019-09-26 15:28:02.1 UTC | 2010-04-24 00:01:00.44 UTC | null | 82,586 | null | 82,586 | null | 1 | 54 | c#|multithreading|waithandle | 28,797 | <p>Create a variable that keeps track of the number of running tasks:</p>
<pre><code>int numberOfTasks = 100;
</code></pre>
<p>Create a signal:</p>
<pre><code>ManualResetEvent signal = new ManualResetEvent(false);
</code></pre>
<p>Decrement the number of tasks whenever a task is finished:</p>
<pre><code>if (Interlocked.Decrement(ref numberOftasks) == 0)
{
</code></pre>
<p>If there is no task remaining, set the signal:</p>
<pre><code> signal.Set();
}
</code></pre>
<p>Meanwhile, somewhere else, wait for the signal to be set:</p>
<pre><code>signal.WaitOne();
</code></pre> |
3,145,607 | php: check if an array has duplicates | <p>I'm sure this is an extremely obvious question, and that there's a function that does exactly this, but I can't seem to find it. In PHP, I'd like to know if my array has duplicates in it, as efficiently as possible. I don't want to remove them like <code>array_unique</code> does, and I don't particularly want to run <code>array_unique</code> and compare it to the original array to see if they're the same, as this seems very inefficient. As far as performance is concerned, the "expected condition" is that the array has no duplicates.</p>
<p>I'd just like to be able to do something like</p>
<pre><code>if (no_dupes($array))
// this deals with arrays without duplicates
else
// this deals with arrays with duplicates
</code></pre>
<p>Is there any obvious function I'm not thinking of?<br>
<a href="https://stackoverflow.com/questions/1170807/how-to-detect-duplicate-values-in-php-array">How to detect duplicate values in PHP array?</a><br>
has the right title, and is a very similar question, however if you actually read the question, he's looking for array_count_values.</p> | 3,145,660 | 17 | 7 | null | 2010-06-29 23:52:10.417 UTC | 15 | 2022-05-06 06:06:55.193 UTC | 2017-11-30 22:31:29.413 UTC | null | 42,223 | null | 146,587 | null | 1 | 83 | php|arrays|duplicates | 131,181 | <p>You can do: </p>
<pre class="lang-php prettyprint-override"><code>function has_dupes($array) {
$dupe_array = array();
foreach ($array as $val) {
if (++$dupe_array[$val] > 1) {
return true;
}
}
return false;
}
</code></pre> |
42,379,751 | How do I find the percentage of something in R? | <p>I am really new at R and this is probably a really basic question but let's say I have a data set with 2 columns that has students that are composed of males and female. One column has the student, and the other column is gender. How do I find the percentage of each? </p> | 42,380,082 | 4 | 1 | null | 2017-02-21 23:09:56.347 UTC | 3 | 2019-03-05 09:51:52.353 UTC | null | null | null | null | 7,601,610 | null | 1 | 3 | r | 77,582 | <p>This is probably not the most efficient way to do this, but this is one way to solve the problem.</p>
<p>First you have to create a data.frame. How is an artificial one: </p>
<pre><code>students <- data.frame(student = c("Carla", "Josh", "Amanda","Gabriel", "Shannon", "Tiffany"), gender = c("Female", "Male", "Female", "Male", "Female", "Female")
View(students)
</code></pre>
<p>Then I use prop table which gives me a proportion table or the ratios the columns in the matrix, and I coerce it to a data.frame because I love data.frames, and I have to multiply by 100 to turn the ratios from the prop table as they would be as percentages.</p>
<pre><code>tablature <- as.data.frame.matrix(prop.table(table(students)) * 100)
tablature
</code></pre>
<p>I decided to call my data frame table tablature.
So it says "Amanda" is 16 + (2 / 3) % on the female column. Basically that means that she is a Female and thus 0 for male, and my data.frame has 6 students so (1 / 6) * 100 makes her 16.667 percent of the set. </p>
<p>Now what percentage of females and males are there?
Two ways: 1) Get the number of each set at the same time with the apply function, or get the number of each set one at a time, and we should use the sum function now. </p>
<pre><code>apply(tablature, 2, FUN = sum)
</code></pre>
<p>Female Male </p>
<p>66.66667 33.33333</p>
<p>Imagine that in terms of percentages. </p>
<p>Where 2 tablature is the proportion table dataframe that I am applying the sum function to across the columns (2 for columns or 1 for rows).</p>
<p>So if you just eyeball the small amount of data, you can see that there are 2 / 6 = 33.3333% males in the data.frame students, and 4 / 6 = 66.66667 % females in the data.frame so I did the calculation correctly. </p>
<p>Alternatively,</p>
<pre><code>sum(tablature$Female)
[1] 66.66667
sum(tablature$Male)
[1] 33.33333
</code></pre>
<p>And you can make a barplot. As I formatted it, you would have to refer to it as a matrix to get a barplot. </p>
<p>And from here you can make a stacked visual comparison of Gender barplot. </p>
<pre><code>barplot(as.matrix(tablature), xlab = "Gender", main = "Barplot comparison of Gender Among Students", ylab = "Percentages of Student Group")
</code></pre>
<p>It's stacking because R made each student a box of 16.6667%. </p>
<p>To be honest it looks better if you just plot the the output of the apply function. Of course you could save it to a variable. But naahhh ... </p>
<pre><code>barplot(apply(tablature, 2, FUN = sum), col = c("green", "blue"),xlab = "Gender", ylab = "Percentage of Total Students", main = "Barplot showing the Percentages of Gender Represented Among Students", cex.main = 1)
</code></pre>
<p>Now it doesn't stack. </p>
<p><a href="https://i.stack.imgur.com/sy8Rm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sy8Rm.png" alt="So Here is a visual representation of what I just calculated"></a></p> |
40,142,331 | How to request Location Permission at runtime | <p>In the manifest file I added permissions coarse and fine, and when I run on device with Android 6, nothing happens! I try
everything but no way to get location updates...</p>
<p>What am I doing wrong?</p>
<pre><code>public class MainActivity extends AppCompatActivity implements LocationListener {
LocationManager locationManager;
String provider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
Log.i("Location Info", "Location achieved!");
} else {
Log.i("Location Info", "No location :(");
}
}
@Override
protected void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
@Override
protected void onPause() {
super.onPause();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.removeUpdates(this);
}
@Override
public void onLocationChanged(Location location) {
Double lat = location.getLatitude();
Double lng = location.getLongitude();
Log.i("Location info: Lat", lat.toString());
Log.i("Location info: Lng", lng.toString());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
public void getLocation(View view) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(provider);
onLocationChanged(location);
}
}
</code></pre> | 40,142,454 | 8 | 0 | null | 2016-10-19 22:09:13.217 UTC | 44 | 2021-10-01 15:24:50.86 UTC | 2019-02-06 04:45:08.63 UTC | null | 4,409,409 | null | 7,044,752 | null | 1 | 99 | java|android | 212,888 | <p>You need to actually request the Location permission at runtime (notice the comments in your code stating this).</p>
<p><strong>Updated with Kotlin and background location for API 31 (Android 12):</strong></p>
<p>Starting with API 30 background location must be requested separately.
This example is using <code>targetSdk 31</code> and <code>compileSdk 31</code>.
Note that it's possible to bundle the background location request along with the main location request on API 29, however to do that you would need to maintain three separate code paths.<br />
It's easier to just break it out to separate requests for 29 and above.</p>
<p>Be sure to include the latest location services in the app level gradle (18.0.0 at the time of writing):</p>
<pre><code>implementation "com.google.android.gms:play-services-location:18.0.0"
</code></pre>
<p>Include the location permissions in the manifest:</p>
<pre><code><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
</code></pre>
<p>This is a simplified example that does handle most cases, but in a simplified way. In the case where a user chooses "Don't ask again", on the next app launch it will open up the settings for the user to manually enable the permission.</p>
<p>Full activity code:</p>
<pre class="lang-kotlin prettyprint-override"><code>import android.Manifest
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Looper
import android.provider.Settings
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.android.gms.location.*
class MainActivity : AppCompatActivity() {
private var fusedLocationProvider: FusedLocationProviderClient? = null
private val locationRequest: LocationRequest = LocationRequest.create().apply {
interval = 30
fastestInterval = 10
priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
maxWaitTime = 60
}
private var locationCallback: LocationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
val locationList = locationResult.locations
if (locationList.isNotEmpty()) {
//The last location in the list is the newest
val location = locationList.last()
Toast.makeText(
this@MainActivity,
"Got Location: " + location.toString(),
Toast.LENGTH_LONG
)
.show()
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fusedLocationProvider = LocationServices.getFusedLocationProviderClient(this)
checkLocationPermission()
}
override fun onResume() {
super.onResume()
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED
) {
fusedLocationProvider?.requestLocationUpdates(
locationRequest,
locationCallback,
Looper.getMainLooper()
)
}
}
override fun onPause() {
super.onPause()
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
)
== PackageManager.PERMISSION_GRANTED
) {
fusedLocationProvider?.removeLocationUpdates(locationCallback)
}
}
private fun checkLocationPermission() {
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(
this,
Manifest.permission.ACCESS_FINE_LOCATION
)
) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton(
"OK"
) { _, _ ->
//Prompt the user once explanation has been shown
requestLocationPermission()
}
.create()
.show()
} else {
// No explanation needed, we can request the permission.
requestLocationPermission()
}
} else {
checkBackgroundLocation()
}
}
private fun checkBackgroundLocation() {
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_BACKGROUND_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
requestBackgroundLocationPermission()
}
}
private fun requestLocationPermission() {
ActivityCompat.requestPermissions(
this,
arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
),
MY_PERMISSIONS_REQUEST_LOCATION
)
}
private fun requestBackgroundLocationPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ActivityCompat.requestPermissions(
this,
arrayOf(
Manifest.permission.ACCESS_BACKGROUND_LOCATION
),
MY_PERMISSIONS_REQUEST_BACKGROUND_LOCATION
)
} else {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
MY_PERMISSIONS_REQUEST_LOCATION
)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
when (requestCode) {
MY_PERMISSIONS_REQUEST_LOCATION -> {
// If request is cancelled, the result arrays are empty.
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
fusedLocationProvider?.requestLocationUpdates(
locationRequest,
locationCallback,
Looper.getMainLooper()
)
// Now check background location
checkBackgroundLocation()
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show()
// Check if we are in a state where the user has denied the permission and
// selected Don't ask again
if (!ActivityCompat.shouldShowRequestPermissionRationale(
this,
Manifest.permission.ACCESS_FINE_LOCATION
)
) {
startActivity(
Intent(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", this.packageName, null),
),
)
}
}
return
}
MY_PERMISSIONS_REQUEST_BACKGROUND_LOCATION -> {
// If request is cancelled, the result arrays are empty.
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
fusedLocationProvider?.requestLocationUpdates(
locationRequest,
locationCallback,
Looper.getMainLooper()
)
Toast.makeText(
this,
"Granted Background Location Permission",
Toast.LENGTH_LONG
).show()
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show()
}
return
}
}
}
companion object {
private const val MY_PERMISSIONS_REQUEST_LOCATION = 99
private const val MY_PERMISSIONS_REQUEST_BACKGROUND_LOCATION = 66
}
}
</code></pre>
<p>On Android 10 (API 29) it will give the user the choice to grant background location after the initial location request:</p>
<p><a href="https://i.stack.imgur.com/el9pa.png" rel="noreferrer"><img src="https://i.stack.imgur.com/el9pa.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/1OfF1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1OfF1.png" alt="enter image description here" /></a></p>
<p>On Android 12 (API 31) it will do the same, but the interface is different:</p>
<p><a href="https://i.stack.imgur.com/XvqYG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XvqYG.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/hmvvN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hmvvN.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/sIeKt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sIeKt.png" alt="enter image description here" /></a></p>
<p><strong>Original Answer in Java:</strong></p>
<p>Here is tested and working code to request the Location permission.</p>
<p>Put this code in the Activity:</p>
<pre class="lang-java prettyprint-override"><code>public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle(R.string.title_location_permission)
.setMessage(R.string.text_location_permission)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}
}
</code></pre>
<p>Then call the <code>checkLocationPermission()</code> method in <code>onCreate()</code>:</p>
<pre><code>@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//.........
checkLocationPermission();
}
</code></pre>
<p>You can then use <code>onResume()</code> and <code>onPause()</code> exactly as it is in the question.</p>
<p>Here is a condensed version that is a bit more clean:</p>
<pre><code>@Override
protected void onResume() {
super.onResume();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
}
@Override
protected void onPause() {
super.onPause();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
locationManager.removeUpdates(this);
}
}
</code></pre> |
10,338,020 | Sencha Touch 2 android performance | <p>I am hearing that sencha in general, by the mere fact of using javascript, has performance issues on android devices.</p>
<p>I am familiar with limitations of the android webview object, but I was wondering if these performance claims have any merit, especially with Sencha Touch 2 being out</p>
<p>Although I don't have a lower end android device, I was looking through the Sencha Touch 2 gallery and could not find free android apps very easily, so perhaps you can explain your experience with Sencha Touch 2 on Android and what you did to make it faster</p> | 10,338,449 | 1 | 0 | null | 2012-04-26 17:01:11.213 UTC | 11 | 2014-05-02 16:52:31.303 UTC | null | null | null | null | 727,429 | null | 1 | 13 | javascript|android|extjs|webview|sencha-touch-2 | 9,980 | <p>To my experience so far, there are some crucial points to keep in mind when developing Sencha Touch 2 applications with as best performance as possible:</p>
<ol>
<li><p>To optimize application startup time:</p>
<ul>
<li>Compress your JS & CSS files. Remove any unused JS functions or CSS mixins (this can be easily done through SASS/Compass). For more details, please read this: <a href="http://www.sencha.com/blog/an-introduction-to-theming-sencha-touch" rel="nofollow noreferrer">http://www.sencha.com/blog/an-introduction-to-theming-sencha-touch</a></li>
<li>Load external JS files dynamically, there's already a good topic here: <a href="https://stackoverflow.com/questions/10334893/what-is-the-proper-way-to-load-an-external-javascript-in-sencha-touch-2">What is the proper way to load an external javascript in Sencha Touch 2</a></li>
</ul></li>
<li><p>To optimize application performance:</p>
<ul>
<li>Keep your DOM structure as small as possible. Inactive views should be destroyed (and dynamically added to your Container later if needed).</li>
<li>Avoid using too many CSS3 properties since they are very slow on Android devices.</li>
<li>For any scrollviews, overscroll should be disabled on Android. I've tested many Sencha Touch 2 applications on Android devices and overscroll causes badly unpleasant experience because of delays and lags. (tested on Galaxy Tab, Nexus S, and some HTCs)</li>
</ul></li>
</ol>
<p>There's also a topic here which is quite relevant to your concern:</p>
<p><a href="https://stackoverflow.com/questions/10085637/phonegap-1-4-wrapping-sencha-touch-2-x-what-about-performance/10085756#10085756">PhoneGap 1.4 wrapping Sencha Touch 2.X - What about performance?</a></p>
<p>Hope it helps.</p>
<p><strong><em>edited on Feb, 12th 2014</strong>: It has been nearly 2 years since I posted this answer (i.e. more than 3 years I have been working with Sencha Touch) and I have to say that Sencha Touch performance on Android is sadly unacceptable. Sometimes I was stuck in the thought that I'm not fully mastering the best practices, but I think it's not the reason. Or at least, it will took us years to develop a large-scale Sencha Touch app which has equal "look and feel" as native apps because the tricks take us so much time.</em></p>
<p><em>So in shorts, if you are targetting iOS or your app is very tiny, it's okay. But for big apps on Android, I personally don't go with Sencha Touch.</em></p> |
32,615,861 | Get week number in month from date in PHP? | <p>I have an array of random dates (not coming from MySQL). I need to group them by the week as Week1, Week2, and so on upto Week5.</p>
<p>What I have is this: </p>
<pre><code>$dates = array('2015-09-01','2015-09-05','2015-09-06','2015-09-15','2015-09-17');
</code></pre>
<p>What I need is a function to get the week number of the month by providing the date.</p>
<p>I know that I can get the weeknumber by doing
<code>date('W',strtotime('2015-09-01'));</code>
but this week number is the number between year (1-52) but I need the week number of the month only, e.g. in Sep 2015 there are 5 weeks:</p>
<ul>
<li>Week1 = 1st to 5th </li>
<li>Week2 = 6th to 12th</li>
<li>Week3 = 13th to 19th</li>
<li>Week4 = 20th to 26th</li>
<li>Week5 = 27th to 30th</li>
</ul>
<p>I should be able to get the week Week1 by just providing the date
e.g.</p>
<pre><code>$weekNumber = getWeekNumber('2015-09-01') //output 1;
$weekNumber = getWeekNumber('2015-09-17') //output 3;
</code></pre> | 32,624,747 | 19 | 1 | null | 2015-09-16 18:18:28.357 UTC | 8 | 2021-08-03 16:48:48.513 UTC | 2015-09-17 08:18:24.89 UTC | null | 2,200,659 | null | 4,105,396 | null | 1 | 19 | php|arrays|date|week-number | 53,266 | <p>I think this relationship should be true and come in handy:</p>
<pre><code>Week of the month = Week of the year - Week of the year of first day of month + 1
</code></pre>
<p>We also need to make sure that "overlapping" weeks from the previous year are handeled correctly - if January 1st is in week 52 or 53, it should be counted as week 0. In a similar fashion, if a day in December is in the first week of the next year, it should be counted as 53. (Previous versions of this answer failed to do this properly.)</p>
<pre><code><?php
function weekOfMonth($date) {
//Get the first day of the month.
$firstOfMonth = strtotime(date("Y-m-01", $date));
//Apply above formula.
return weekOfYear($date) - weekOfYear($firstOfMonth) + 1;
}
function weekOfYear($date) {
$weekOfYear = intval(date("W", $date));
if (date('n', $date) == "1" && $weekOfYear > 51) {
// It's the last week of the previos year.
return 0;
}
else if (date('n', $date) == "12" && $weekOfYear == 1) {
// It's the first week of the next year.
return 53;
}
else {
// It's a "normal" week.
return $weekOfYear;
}
}
// A few test cases.
echo weekOfMonth(strtotime("2020-04-12")) . " "; // 2
echo weekOfMonth(strtotime("2020-12-31")) . " "; // 5
echo weekOfMonth(strtotime("2020-01-02")) . " "; // 1
echo weekOfMonth(strtotime("2021-01-28")) . " "; // 5
echo weekOfMonth(strtotime("2018-12-31")) . " "; // 6
</code></pre>
<p>To get weeks that starts with sunday, simply replace <code>date("W", ...)</code> with <code>strftime("%U", ...)</code>.</p> |
18,960,548 | Disable dark fading in Navigation Drawer | <p>Is there a way to disable the dark fading effect for the background view in the Navigation Drawer View in Android?</p> | 19,099,220 | 4 | 0 | null | 2013-09-23 13:29:37.317 UTC | 12 | 2019-11-15 09:42:49.11 UTC | null | null | null | null | 667,175 | null | 1 | 52 | java|android|android-layout|android-view|navigation-drawer | 19,332 | <p>You can use <code>setScrimColor(int color)</code> method. As default color is used <code>0x99000000</code>. So if you don't want <code>faded</code> background, set <code>transparent</code> color in this method.</p>
<pre><code>mDrawerLayout.setScrimColor(getResources().getColor(android.R.color.transparent));
</code></pre> |
27,940,042 | how to change font size and font name of uisegmentedcontrol programmatically on swift? | <p>How to change font size and font name of uisegmentedcontrol programmatically? I used swift.</p>
<p>Here is my code:</p>
<pre><code>self.mysegmentedControl = UISegmentedControl(items: [
NSLocalizedString("Aaaaaa", comment: ""),
NSLocalizedString("Bbbbbb", comment: ""),
NSLocalizedString("Cccccc", comment: ""),
NSLocalizedString("Dddddd", comment: ""),
NSLocalizedString("Eeeeee", comment: ""),
])
self.mysegmentedControl.addTarget(self, action: "mysegmentedControlDidChange:", forControlEvents: .ValueChanged)
self.mysegmentedControl.selectedSegmentIndex = 0
</code></pre>
<p>regards.</p> | 27,940,348 | 15 | 0 | null | 2015-01-14 09:52:49.96 UTC | 7 | 2020-06-15 20:42:04.553 UTC | null | null | null | null | 1,858,725 | null | 1 | 43 | swift|uisegmentedcontrol | 44,238 | <p>UI can use control appearance, best place to add it is in app delegate, <code>didFinishLaunchingWithOptions</code> method, use this if you want to set up the same attribute to every UISegmentedControls in your project just once:</p>
<pre><code>let attr = NSDictionary(object: UIFont(name: "HelveticaNeue-Bold", size: 16.0)!, forKey: NSFontAttributeName)
UISegmentedControl.appearance().setTitleTextAttributes(attr as [NSObject : AnyObject] , forState: .Normal)
</code></pre>
<p>But if you are going to set up attributes to just one UISegmentedControl or if you want to change it more often base on some condition use this, UISegmentedControl method:</p>
<pre><code>func setTitleTextAttributes(_ attributes: [NSObject : AnyObject]?,
forState state: UIControlState)
</code></pre>
<p>Example:</p>
<pre><code>let attr = NSDictionary(object: UIFont(name: "HelveticaNeue-Bold", size: 16.0)!, forKey: NSFontAttributeName)
seg.setTitleTextAttributes(attr as [NSObject : AnyObject] , forState: .Normal)
</code></pre> |
1,241,575 | What is the NSObject isEqual: and hash default function? | <p>I have a database model class that is a <code>NSObject</code>. I have a set of these objects in a <code>NSMutableArray</code>. I use <code>indexOfObject:</code> to find a match. Problem is the model object's memory address changes. So I am overriding the <code>hash</code> method to return the model's row ID. This however does not fix it. I also have to override the <code>isEqual:</code> method to compare the value of the <code>hash</code> method.</p>
<p><strong>What does the <code>isEqual:</code> method use to determine equality by default?</strong></p>
<p>I'm assuming it uses the memory address. After reading the <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/isEqual:" rel="noreferrer"><code>isEqual:</code></a> documentation I thought it used the value from the <code>hash</code> method. Obviously, that is not the case as my attempt to override that value did not solve my initial problem.</p> | 4,253,490 | 3 | 7 | null | 2009-08-06 21:24:16.933 UTC | 3 | 2014-10-01 02:43:03.543 UTC | 2013-08-27 21:00:03.103 UTC | null | 1,709,587 | null | 143,225 | null | 1 | 32 | objective-c|nsarray|nsobject | 13,727 | <p>As you've correctly guessed, <code>NSObject</code>'s default <code>isEqual:</code> behaviour is comparing the memory address of the object. Strangely, this is not presently documented in the <a href="https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSObject_Class/Reference/Reference.html" rel="noreferrer">NSObject Class Reference</a>, but it is documented in the <a href="https://developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/Introspection/Introspection.html#//apple_ref/doc/uid/TP40010810-CH9-SW61" rel="noreferrer">Introspection</a> documentation, which states:</p>
<blockquote>
<p>The default <code>NSObject</code> implementation of <code>isEqual:</code> simply checks for pointer equality.</p>
</blockquote>
<p>Of course, as you are doubtless aware, subclasses of <code>NSObject</code> can override <code>isEqual:</code> to behave differently. For example, <code>NSString</code>'s <code>isEqual:</code> method, when passed another <code>NSString</code>, will first check the address and then check for an exact literal match between the strings.</p> |
1,138,503 | Good C/C++ connector library for PostgreSQL | <p>My application is a commercial GIS C++ application, and I'm looking for a robust/easy to use connector for Postgresq. (Side note: I also plan to use PostGIS)</p>
<p>Does anyone have any recommendations based on your experience? A plus would be if you have tried out various ones.</p>
<p>I have looked at:</p>
<ol>
<li><a href="http://www.postgresql.org/docs/8.3/static/client-interfaces.html" rel="noreferrer">Postgres's C client</a></li>
<li><a href="http://pqxx.org/development/libpqxx/" rel="noreferrer">pqxx</a></li>
<li><a href="http://doc.trolltech.com/4.5/qtsql.html" rel="noreferrer">QSql</a></li>
</ol>
<p><strong>EDIT</strong>
Also, does anyone know what's a good admin GUI tool? I see a community list <a href="http://wiki.postgresql.org/wiki/Community_Guide_to_PostgreSQL_GUI_Tools" rel="noreferrer">here</a>. But there are so many! I'm developing on Windows, and dont mind paying for commercial tools.
Someone in another Stackoverflow post suggested <a href="http://www.sqlmaestro.com/products/postgresql/maestro/" rel="noreferrer">Maestro</a>.</p> | 1,138,516 | 3 | 1 | null | 2009-07-16 15:41:35.207 UTC | 14 | 2020-04-18 19:08:41.647 UTC | 2009-07-17 11:49:04.493 UTC | null | 15,785 | null | 65,313 | null | 1 | 34 | c++|postgresql | 49,356 | <p><a href="http://www.postgresql.org/docs/7.2/static/libpqplusplus.html" rel="noreferrer">libpq++</a> is one provide very good connector for PostgreSQL</p>
<p><a href="http://www.sqlapi.com/" rel="noreferrer">SQLAPI++</a> is a C++ library for accessing multiple SQL databases (Oracle, SQL Server, DB2, Sybase, Informix, InterBase, SQLBase, MySQL, PostgreSQL and ODBC, SQLite).</p>
<p><a href="http://ostatic.com/a-dbc" rel="noreferrer">Abstract Database Connector</a> is a C/C++ library for making connections to several databases (MySQL, mSQL, PostgreSQL, Interbase, Informix, BDE, ODBC). It runs on Linux, UNIX, BeOS, and Windows, and a dynamic driver loader for ELF OSes is under development</p>
<p><a href="http://www.navicat.com/download/" rel="noreferrer">Navicat</a> is Nice GUI tool for PostgrSQL</p> |
22,242,172 | In ScalaTest is there any difference between `should`, `can`, `must` | <p>Just started using ScalaTest and I quite like it.</p>
<p>By just reading <a href="http://www.scalatest.org/user_guide/">the docs</a> I have thus far been unable to figure out whether there is any <em>substantial</em> difference between the <code>can</code>, <code>should</code> and <code>must</code> clauses for a <code>FlatSpec</code>.</p>
<p>In particular, I'm wondering whether a <code>must</code> failure is treated any differently from a <code>should</code> one - or it's just "syntactic sugar" to make the tests better self-documented.</p> | 22,242,538 | 1 | 0 | null | 2014-03-07 05:22:43.437 UTC | 3 | 2014-03-07 05:48:49.817 UTC | null | null | null | null | 1,263,473 | null | 1 | 30 | unit-testing|scala|scalatest | 5,491 | <p><strong><code>should</code> and <code>must</code> are the same semantically</strong>. But it's not about better documentation, <strong>it's basically just down to personal stylistic preference</strong> (I prefer <code>must</code> for example).</p>
<p><strong><code>can</code> is a little different</strong>. You can't (nomen omen) use it directly as a matcher, it's only available in a test descriptor. Quote from <a href="http://doc.scalatest.org/2.1.0/index.html#org.scalatest.FlatSpec"><code>FlatSpec</code></a>:</p>
<blockquote>
<p>Note: you can use must or can as well as should in a FlatSpec. For
example, instead of it should "pop..., you could write it must "pop...
or it can "pop....</p>
</blockquote>
<p>(the same applies for <a href="http://doc.scalatest.org/2.1.0/index.html#org.scalatest.WordSpec"><code>WordSpec</code></a> and the <a href="http://doc.scalatest.org/2.1.0/index.html#org.scalatest.fixture.WordSpec">two</a> <a href="http://doc.scalatest.org/2.1.0/index.html#org.scalatest.fixture.FlatSpec">corresponding</a> fixture classes)</p>
<p>Note that for a short time (in ScalaTest 2.0.x I think), the use of <code>must</code> was deprecated, however, in 2.1.0, the decision <a href="http://doc.scalatest.org/2.1.0/index.html#org.scalatest.Matchers">has been reverted</a>:</p>
<blockquote>
<p>Resurrected MustMatchers in package org.scalatest. Changed deprecation
warning for org.scalatest.matchers.MustMatchers to suggest using
org.scalatest.MustMatchers instead of org.scalatest.Matchers, which
was the suggestion in 2.0. Apologies to must users who migrated to
should already when upgrading to 2.0.</p>
</blockquote> |
6,455,850 | The relative virtual path '' is not allowed here | <p>Any ideas what this problem is? cheers</p>
<p><img src="https://i.stack.imgur.com/8XSEN.png" alt="enter image description here"></p> | 6,455,883 | 1 | 0 | null | 2011-06-23 14:36:19.13 UTC | 6 | 2018-09-19 08:48:26.247 UTC | null | null | null | null | 583,341 | null | 1 | 66 | asp.net|visual-studio-2010 | 58,430 | <p>It looks like you're trying to pass <a href="http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath.aspx" rel="noreferrer"><code>MapPath</code></a> a page-relative path (<code>../.....</code>) instead of a virtual path (<code>~/.....</code>).</p> |
42,103,144 | How to align rows in matplotlib legend with 2 columns | <p>I have an issue where some mathtext formatting is making some labels take up more vertical space than others, which causes them to not line up when placed in two columns in the legend. This is particularly important because the rows are also used to indicate related data. </p>
<p>Here is an example:</p>
<pre><code>import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.mathtext as mathtext
mpl.rc("font", family="Times New Roman",weight='normal')
plt.rcParams.update({'mathtext.default': 'regular' })
plt.plot(1,1, label='A')
plt.plot(2,2, label='B')
plt.plot(3,3, label='C')
plt.plot(4,4,label='$A_{x}^{y}$')
plt.plot(5,5,label='$B_{x}^{y}$')
plt.plot(6,6,label='$C_{x}^{y}$')
plt.legend(fontsize='xx-large', ncol=2)
plt.show()
</code></pre>
<p>This generates a figure like so:
<a href="https://i.stack.imgur.com/Rmp2x.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Rmp2x.png" alt="enter image description here"></a></p>
<p>For a while, I was able to "fake it" a bit by adding some empty subscripts and superscripts, however this only works when the plot is exported to pdf. It does not appear to work when exporting to png. How can I spread out the first column of labels so that they line up with the second column? </p> | 42,170,161 | 1 | 2 | null | 2017-02-08 01:33:08.003 UTC | 4 | 2017-02-10 23:45:00.043 UTC | null | null | null | null | 5,429,242 | null | 1 | 28 | python|matplotlib | 54,492 | <p>You could set the <code>handleheight</code> keyword argument to a number which is just large enough that the height of the handle is larger than the space taken by the font. This makes the text appear aligned. Doing so may require to set the <code>labelspacing</code> to a small number, in order not to make the legend appear too big.</p>
<pre><code>plt.legend(fontsize='xx-large', ncol=2,handleheight=2.4, labelspacing=0.05)
</code></pre>
<p><a href="https://i.stack.imgur.com/pcewZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pcewZ.png" alt="enter image description here"></a></p>
<p>The drawback of this method, as can be seen in the picture, is that the lines shift upwards compared to the text's baseline. It would probably depent on the usage case if this is acceptable or not.</p>
<p>In case it is not, one needs to dig a little deeper. The following subclasses <code>HandlerLine2D</code> (which is the Handler for Lines) in order to set a slightly different position to the lines. Depending on the total legend size, font size etc. one would need to adapt the number <code>xx</code> in the <code>SymHandler</code> class.</p>
<pre><code>from matplotlib.legend_handler import HandlerLine2D
import matplotlib.lines
class SymHandler(HandlerLine2D):
def create_artists(self, legend, orig_handle,xdescent, ydescent, width, height, fontsize, trans):
xx= 0.6*height
return super(SymHandler, self).create_artists(legend, orig_handle,xdescent, xx, width, height, fontsize, trans)
leg = plt.legend(handler_map={matplotlib.lines.Line2D: SymHandler()},
fontsize='xx-large', ncol=2,handleheight=2.4, labelspacing=0.05)
</code></pre>
<p><a href="https://i.stack.imgur.com/Rd1ga.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Rd1ga.png" alt="enter image description here"></a></p> |
35,029,984 | SystemVerilog wait() statement | <p>Is the following code is supported in SystemVerilog?</p>
<pre><code>int cnt = 0;
wait( cnt == (cnt+1) )
</code></pre>
<p>Could any one point me the section in LRM?</p> | 35,205,933 | 4 | 1 | null | 2016-01-27 06:08:44.62 UTC | null | 2017-09-05 14:11:44.457 UTC | 2016-01-27 06:59:05.04 UTC | null | 2,755,607 | null | 3,510,047 | null | 1 | 0 | verilog|system-verilog|uvm | 43,425 | <p>This is supported. But the main question is, what will you get by such wait statement, as <strong>this statement will never be evaluated as "true"</strong>.</p>
<p>May be I can help you, if you provide more details on, what you exactly want to do through this wait statement.</p>
<p>Meanwhile, here is the code, as per your wait statement, with it's output. This will help you to understand, what this wait statement will do: </p>
<pre><code>// Sample code, as per your wait statement
module top();
int cnt;
bit clk;
always #5 clk = ~clk;
always @ (posedge clk)
cnt <= cnt + 1;
initial
begin
$display("***** Before wait *****");
wait(cnt == (cnt + 1))
$display("***** After wait *****");
end
initial #100 $finish;
initial $monitor("cnt - %0d", cnt);
endmodule
// Output of this sample code
***** Before wait *****
cnt - 0
cnt - 1
cnt - 2
cnt - 3
cnt - 4
cnt - 5
cnt - 6
cnt - 7
cnt - 8
cnt - 9
cnt - 10
$finish called from file "testbench.sv", line 20.
$finish at simulation time 100
</code></pre> |
36,014,777 | docker ps shows empty list | <p>I built a docker image from a docker file. Build said it succeeded. But when I try to show docker containers through <code>docker ps</code> (also tried <code>docker ps -a</code>), it shows an empty list. What is weird is that I'm still able to somehow push my docker image to dockerhub by calling <code>docker push "container name"</code>.</p>
<p>I wonder what's going on? I'm on Windows 7, and just installed the newest version of dockertoolbox.</p> | 36,014,824 | 7 | 1 | null | 2016-03-15 14:56:25.513 UTC | 10 | 2022-09-02 08:27:47.323 UTC | 2016-03-15 15:59:41.003 UTC | null | 4,512,451 | null | 4,662,347 | null | 1 | 78 | docker|docker-toolbox | 109,932 | <p><code>docker ps</code> shows (running) containers. <code>docker images</code> shows images.</p>
<p>A successfully build docker image should appear in the list which <code>docker images</code> generates. But only a running container (which is an instance of an image) will appear in the list from <code>docker ps</code> (use <code>docker ps -a</code> to also see stopped containers). To start a container from your image, use <code>docker run</code>.</p> |
35,841,241 | Docker-compose named mounted volume | <p>In order to keep track of the volumes used by docker-compose, I'd like to use named volumes. This works great for 'normal' volumes like</p>
<pre class="lang-yaml prettyprint-override"><code>version: 2
services:
example-app:
volume:
-named_vol:/dir/in/container/volume
volumes:
named_vol:
</code></pre>
<p>But I can't figure out how to make it work when mounting the local host.
I'm looking for something like:</p>
<pre class="lang-yaml prettyprint-override"><code>version: 2
services:
example-app:
volume:
-named_homedir:/dir/in/container/volume
volumes:
named_homedir: /c/Users/
</code></pre>
<p>or</p>
<pre class="lang-yaml prettyprint-override"><code>version: 2
services:
example-app:
volume:
-/c/Users/:/home/dir/in/container/ --name named_homedir
</code></pre>
<p>is this in any way possible or am I stuck with anonymous volumes for mounted ones?</p> | 40,030,535 | 5 | 2 | null | 2016-03-07 10:23:59.4 UTC | 29 | 2020-12-08 21:09:05.773 UTC | 2020-07-24 02:34:54.013 UTC | null | 1,402,846 | null | 15,355 | null | 1 | 91 | docker-compose|docker-volume | 86,275 | <p>As you can read in this GitHub issue, <em>mounting named volumes</em> <a href="https://github.com/docker/docker/issues/19990#issuecomment-248955005" rel="noreferrer">now is a thing</a> … since 1.11 or 1.12.). <a href="https://docs.docker.com/engine/reference/commandline/volume_create/#/driver-specific-options" rel="noreferrer">Driver specific options</a> are documented. Some notes from the GitHub thread:</p>
<pre><code>docker volume create --opt type=none --opt device=<host path> --opt o=bind
</code></pre>
<blockquote>
<p>If the host path does not exist, it will not be created.</p>
</blockquote>
<blockquote>
<p>Options are passed in literally to the mount syscall. We may add special cases for certain "types" because they are awkward to use... like the nfs example [referenced above].</p>
</blockquote>
<p><em><sup>– @cpuguy83</sup></em></p>
<p>To address your specific question about how to use that in compose, you write under your <code>volumes</code> section:</p>
<pre><code>my-named-volume:
driver_opts:
type: none
device: /home/full/path #NOTE needs full path (~ doesn't work)
o: bind
</code></pre>
<p>This is because as cpuguy83 wrote in the github thread linked, the options are (under the hood) passed directly to the <code>mount</code> command.</p>
<p><em>EDIT:</em> As commented by…</p>
<ul>
<li><p>…@villasv, you can use <code>${PWD}</code> for relative paths.</p>
</li>
<li><p>…@mikeyjk, you might need to delete preexisting volumes:</p>
<pre><code> docker volume rm $(docker volume ls -q)
OR
docker volume prune
</code></pre>
</li>
<li><p>…@Camron Hudson, in case you have <code>no such file or directory</code> errors showing up, you might want to read <a href="https://stackoverflow.com/q/56531493/376483">this SO question/ answer</a> as Docker does not follow symlinks and there might be permission issues with your local file system.</p>
</li>
</ul> |
6,207,176 | Compiling FreeType to DLL (as opposed to static library) | <p>I want to use FreeType in a c# project. I found this <a href="http://www.koders.com/csharp/fid840ED1F892217853EE1DD8692B953A84E1D5C2AE.aspx" rel="noreferrer">binding</a>, but I still need a freetype.dll. I usually use a static library in my c++ projects, so I never compiled one. Opening the freetype-solution (VS2010) I noticed that there is no configuration for a dynamic library - just static ones. I tried to make my own configuration and got it to generate a freetype.dll. If I use it with the c#-binding I get an exception, that the FT_Init_FreeType-entry point was not found. Any idea how I must adjust the freetype-project in order to export those functions?</p> | 7,387,618 | 3 | 0 | null | 2011-06-01 20:23:00.78 UTC | 18 | 2020-07-02 07:21:09.5 UTC | null | null | null | null | 312,632 | null | 1 | 15 | visual-studio-2010|dll|compilation|freetype | 16,519 | <p>If you're ok with an old version (march 2008), you can go to <a href="http://gnuwin32.sourceforge.net/packages/freetype.htm" rel="nofollow noreferrer">FreeType for Windows</a> page, download the latest Binaries package, open the .ZIP, and extract FreeType6.dll from the bin directory. Just rename it appropriately.</p>
<p>If you need a more recent version, here is how you can compile the latest:</p>
<ul>
<li><p>download the latest source (2.4.6 as of today) from <a href="http://sourceforge.net/projects/freetype/files/freetype2/" rel="nofollow noreferrer">http://sourceforge.net/projects/freetype/files/freetype2/</a></p></li>
<li><p>open Visual Studio 2010, and load <code>freetype.sln</code> from the <code>builds\win32\vc2010</code> directory.</p></li>
<li><p>open the project config, and in the <code>General</code> tab, change <code>Configuration Type</code> to <code>Dynamic Library (.dll)</code></p></li>
<li><p>open the <code>ftoption.h</code> file, and add these lines (near the "DLL export compilation" remarks section for example):</p>
<pre><code>#define FT_EXPORT(x) __declspec(dllexport) x
#define FT_BASE(x) __declspec(dllexport) x
</code></pre></li>
<li><p>change the project compilation configuration to "Release".</p></li>
<li><p>compile the project. You should now have a <code>freetype246.dll</code> in the <code>objs\win32\vc2010</code> directory.</p></li>
</ul> |
5,912,240 | Android JUnit Testing ... How to Expect an Exception | <p>I'm attempting to write some tests using the built-in android Junit testing framework. I am running into a problem with a test where I am expecting an exception to be thrown. In JUnit, the annotation for the test method would be: </p>
<p><code>@Test(expected = ArithmeticException.class)</code></p>
<p>However, in Android, this test fails with an ArithmeticException.</p>
<p>I understand that the Android implementation is only a subset of JUnit 3, and doesn't even allow the annotation @Test (must be @SmallTest, @MediumTest, or @LargeTest, and none of those allow for the 'expected=..' parameter), but this seems like a fairly significant test, and seems like the Android testing framework would be seriously lacking if it did not have this feature.</p>
<p><strong>Note :</strong> I tested this by adding the JUnit jar to the project and by adding and the annotations to my test methods. It makes sense to me why the annotations would be completely ignored because the Android framework (runner?) is not looking for that annotation and just ignores it. Basically, I'm just looking for the 'right' way to do this within the framework. </p> | 5,912,555 | 3 | 0 | null | 2011-05-06 13:37:06.76 UTC | 5 | 2018-07-16 13:51:44.107 UTC | 2018-05-31 04:58:18.18 UTC | null | 11,732,320 | null | 561,717 | null | 1 | 61 | android|testing|junit | 29,052 | <p>The standard junit 3 idiom for this sort of test was:</p>
<pre><code>public void testThatMethodThrowsException()
{
try
{
doSomethingThatShouldThrow();
Assert.fail("Should have thrown Arithmetic exception");
}
catch(ArithmeticException e)
{
//success
}
}
</code></pre> |
5,617,703 | Background color in input and text fields | <p>I would like to change the color background in the text and input fields of a form, but when I do this it also affects the submit button! Could it be done in some other way that does not affect the button?</p>
<p>I have used this code:</p>
<pre><code>input, textarea {
background-color: #d1d1d1;
}
</code></pre> | 5,617,741 | 3 | 1 | null | 2011-04-11 06:47:25.55 UTC | 15 | 2022-02-11 03:26:38.137 UTC | 2022-02-11 03:26:38.137 UTC | null | 6,904,888 | null | 637,364 | null | 1 | 92 | css|html-input | 497,724 | <pre><code>input[type="text"], textarea {
background-color : #d1d1d1;
}
</code></pre>
<p>Hope that helps :)</p>
<p><strong>Edit:</strong> working example, <a href="http://jsfiddle.net/C5WxK/" rel="noreferrer">http://jsfiddle.net/C5WxK/</a></p> |
5,619,719 | Write a file on iOS | <p>How do I write a file on iOS? I'm trying to do it with the following code but I'm doing something wrong:</p>
<pre><code>char *saves = "abcd";
NSData *data = [[NSData alloc] initWithBytes:saves length:4];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile"];
[data writeToFile:appFile atomically:YES];
</code></pre>
<p>I have created MyFile.txt on resources.</p> | 5,619,855 | 4 | 1 | null | 2011-04-11 10:05:12.687 UTC | 30 | 2018-01-06 19:38:05.39 UTC | 2014-05-02 21:47:09.213 UTC | null | 642,706 | null | 672,826 | null | 1 | 79 | ios|iphone|file|nsbundle | 139,508 | <p>Your code is working at my end, i have just tested it. Where are you checking your changes? Use Documents directory path. To get path -</p>
<pre><code>NSLog(@"%@",documentsDirectory);
</code></pre>
<p>and copy path from console and then open finder and press Cmd+shift+g and paste path here and then open your file</p> |
2,243,993 | how to execute command line .exe file in java | <ol>
<li>i want to convert an avi file to 3gp
using java program.</li>
<li>For this i am using "E.M. Total
Video Converter Command Line 2.43"
and the command for it is<br>
<strong>"C:\E.M.
TVCC>TVCC -f E:\TestVideo\01.avi -o
E:\OutputFiles\target.3gp"</strong></li>
<li>I got a program to execute command
line exe file on site <a href="http://www.rgagnon.com/javadetails/java-0014.html" rel="noreferrer">http://www.rgagnon.com/javadetails/java-0014.html</a> which is:</li>
</ol>
<h2><strong>Path to executable with spaces in them</strong></h2>
<p>You can include a path for the program to be executed. On the Win plateform, you need to put the path in quotes if the path contains spaces. </p>
<pre><code>public class Test {
public static void main(String[] args) throws Exception {
Process p = Runtime.getRuntime().exec(
"\"c:/program files/windows/notepad.exe\"");
p.waitFor();
}
}
</code></pre>
<p>If you need to pass arguments, it's safer to a String array especially if they contain spaces. </p>
<pre><code>String[] cmd = { "myProgram.exe", "-o=This is an option" };
Runtime.getRuntime().exec(cmd);
</code></pre>
<p>If using the start command and the path of the file to be started contains a space then you must specified a title to the start command. </p>
<pre><code>String fileName = "c:\\Applications\\My Documents\\test.doc";
String[] commands = {"cmd", "/c", "start", "\"DummyTitle\"",fileName};
Runtime.getRuntime().exec(commands);
</code></pre>
<p>***Can anyone help me to put the above command in this code?***I dont know the syntax rules to put that command in the above code.Please help me.</p>
<p>This is the exact java code i am using:</p>
<pre><code>public class Test {
public static void main(String[] args) throws Exception {
String[] cmd = { "C:\\Program Files\\E.M. TVCC\\TVCC.exe", "-f C:\\Program Files\\E.M. TVCC\\01.avi", "-o C:\\Program Files\\E.M. TVCC\\target.3gp" };
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
}
}
</code></pre> | 2,244,077 | 2 | 2 | null | 2010-02-11 11:10:50.077 UTC | 7 | 2015-12-31 10:58:00.503 UTC | 2010-02-12 10:50:58.88 UTC | null | 243,680 | null | 243,680 | null | 1 | 18 | java|command-line|syntax | 74,670 | <p>You've got all the pieces in your question. It's just a matter of putting it all together.</p>
<p>Something such as the following should work: </p>
<pre><code>public class Test {
public static void main(String[] args) throws Exception {
String[] cmd = { "C:\\E.M. TVCC\\TVCC.exe", "-f E:\\TestVideo\\01.avi", "-o E:\\OutputFiles\\target.3gp" };
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
}
}
</code></pre>
<p>That said, hard coding paths like this isn't a good idea, you should read them from somewhere; arguments to your program, a properties file, etc.</p> |
50,352,474 | npm audit only for production dependencies? | <p>Currently, when running <code>npm audit</code> in a project, it checks both the <code>dependencies</code> and the <code>devDependencies</code>. I am looking for a way to only check the <code>dependencies</code>. Is there currently a way to do so?</p> | 59,780,064 | 2 | 2 | null | 2018-05-15 14:13:33.403 UTC | 4 | 2022-07-03 18:29:23.827 UTC | 2021-11-25 12:18:04.677 UTC | null | 79,485 | null | 857,990 | null | 1 | 36 | node.js|security|npm|audit | 10,588 | <p>Support for <code>--production</code> flag was released in npm 6.10.0</p>
<p><a href="https://github.com/npm/cli/pull/202" rel="noreferrer">https://github.com/npm/cli/pull/202</a></p>
<p><code>npm audit --production</code></p>
<p>The <code>--omit</code> flag was added in npm 7.x and is now preferred.</p>
<p><a href="https://docs.npmjs.com/cli/v8/commands/npm-audit/#omit" rel="noreferrer">https://docs.npmjs.com/cli/v8/commands/npm-audit/#omit</a></p>
<p><code>npm audit --omit=dev</code></p> |
32,166,870 | 'img-src' was not explicitly set, so 'default-src' is used as a fallback | <p>Here is my <code>Content-Security-Policy</code> in <code>index.html</code></p>
<pre><code><meta http-equiv="Content-Security-Policy" content="default-src 'self' http://example.com">
</code></pre>
<p>Now i am dynamically setting img src of <code><img id="updateProfilePicPreview" class="profilPicPreview" src="" /></code> as </p>
<pre><code> var smallImage = document.getElementById('updateProfilePicPreview');
smallImage.style.display = 'block';
smallImage.src = "data:image/jpeg;base64," + imageData;
</code></pre>
<p>It shows</p>
<blockquote>
<p>Refused to load the image 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDACgcHiMeGSgjISMtKygw…p+tB/yaKKAIi2TSfjRRVCJFOyIk96rE5NFFDGgoooqBhRRRQA9elIDg5oopgIc+lFFFAH/2Q==' because it violates the following Content Security Policy directive: "default-src 'self' <a href="http://example.com">http://example.com</a>". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.</p>
</blockquote>
<p>So how can i enable setting <code>img</code> src dynamically ?</p>
<p>I was following this example from cordova page:</p>
<pre><code>var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for device API libraries to load
//
document.addEventListener("deviceready",onDeviceReady,false);
// device APIs are available
//
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
//
function onPhotoDataSuccess(imageData) {
// Uncomment to view the base64-encoded image data
// console.log(imageData);
// Get image handle
//
var smallImage = document.getElementById('smallImage');
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The in-line CSS rules are used to resize the image
//
smallImage.src = "data:image/jpeg;base64," + imageData;
}
// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageURI) {
// Uncomment to view the image file URI
// console.log(imageURI);
// Get image handle
//
var largeImage = document.getElementById('largeImage');
// Unhide image elements
//
largeImage.style.display = 'block';
// Show the captured photo
// The in-line CSS rules are used to resize the image
//
largeImage.src = imageURI;
}
// A button will call this function
//
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: destinationType.DATA_URL });
}
// A button will call this function
//
function capturePhotoEdit() {
// Take picture using device camera, allow edit, and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL });
}
// A button will call this function
//
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
// Called if something bad happens.
//
function onFail(message) {
alert('Failed because: ' + message);
}
</code></pre> | 32,166,921 | 1 | 1 | null | 2015-08-23 12:55:16.513 UTC | 14 | 2016-03-16 07:36:25.877 UTC | 2016-03-16 07:36:25.877 UTC | null | 314,334 | null | 1,049,104 | null | 1 | 37 | javascript|html|cordova | 81,226 | <blockquote>
<p>So how can i enable setting img src dynamically ?</p>
</blockquote>
<p>The problem is not setting the src, the problem is setting the src to a data: scheme URI.</p>
<p>Add <code>data:</code> to the list of things allowed by the <a href="http://content-security-policy.com/">content security policy</a>. Either for the default-src or you could define a separate img-src. </p>
<p>In the example below, I have added <code>img-src 'self' data:;</code> to the start of the meta tag in the index.html file.</p>
<pre><code><meta http-equiv="Content-Security-Policy" content="img-src 'self' data:; default-src 'self' http://XX.XX.XX.XX:8084/mypp/">
</code></pre> |
5,627,954 | How do you read a file inside a zip file as text, not bytes? | <p>A simple program for reading a CSV file inside a zip file works in Python 2.7, but not in Python 3.2</p>
<pre><code>$ cat test_zip_file_py3k.py
import csv, sys, zipfile
zip_file = zipfile.ZipFile(sys.argv[1])
items_file = zip_file.open('items.csv', 'rU')
for row in csv.DictReader(items_file):
pass
$ python2.7 test_zip_file_py3k.py ~/data.zip
$ python3.2 test_zip_file_py3k.py ~/data.zip
Traceback (most recent call last):
File "test_zip_file_py3k.py", line 8, in <module>
for row in csv.DictReader(items_file):
File "/home/msabramo/run/lib/python3.2/csv.py", line 109, in __next__
self.fieldnames
File "/home/msabramo/run/lib/python3.2/csv.py", line 96, in fieldnames
self._fieldnames = next(self.reader)
_csv.Error: iterator should return strings, not bytes (did you open the file
in text mode?)
</code></pre>
<p>So the <code>csv</code> module in Python 3 wants to see a text file, but <code>zipfile.ZipFile.open</code> returns a <code>zipfile.ZipExtFile</code> that is always treated as binary data.</p>
<p>How does one make this work in Python 3?</p> | 5,639,960 | 5 | 0 | null | 2011-04-11 21:46:47.813 UTC | 6 | 2022-01-04 18:29:15.867 UTC | 2019-06-26 17:21:38.863 UTC | null | 1,264,804 | null | 638,434 | null | 1 | 40 | csv|python-3.x|zip | 17,569 | <p>I just noticed that <a href="https://stackoverflow.com/questions/5627954/py3k-how-do-you-read-a-file-inside-a-zip-file-as-text-not-bytes/5631786#5631786">Lennart's answer</a> didn't work with Python <strong>3.1</strong>, but it <strong>does</strong> work with <a href="http://www.python.org/download/releases/3.2/" rel="noreferrer">Python <strong>3.2</strong></a>. They've enhanced <a href="http://docs.python.org/py3k/library/zipfile.html#zipfile.ZipFile.open" rel="noreferrer"><code>zipfile.ZipExtFile</code></a> in Python 3.2 (see <a href="http://docs.python.org/dev/whatsnew/3.2.html#gzip-and-zipfile" rel="noreferrer">release notes</a>). These changes appear to make <code>zipfile.ZipExtFile</code> work nicely with <a href="http://docs.python.org/py3k/library/io.html#io.TextIOWrapper" rel="noreferrer"><code>io.TextWrapper</code></a>.</p>
<p>Incidentally, it works in Python 3.1, if you uncomment the hacky lines below to monkey-patch <code>zipfile.ZipExtFile</code>, not that I would recommend this sort of hackery. I include it only to illustrate the essence of what was done in Python 3.2 to make things work nicely.</p>
<pre><code>$ cat test_zip_file_py3k.py
import csv, io, sys, zipfile
zip_file = zipfile.ZipFile(sys.argv[1])
items_file = zip_file.open('items.csv', 'rU')
# items_file.readable = lambda: True
# items_file.writable = lambda: False
# items_file.seekable = lambda: False
# items_file.read1 = items_file.read
items_file = io.TextIOWrapper(items_file)
for idx, row in enumerate(csv.DictReader(items_file)):
print('Processing row {0} -- row = {1}'.format(idx, row))
</code></pre>
<p>If I had to support py3k < 3.2, then I would go with the solution in <a href="https://stackoverflow.com/questions/5627954/py3k-how-do-you-read-a-file-inside-a-zip-file-as-text-not-bytes/5639578#5639578">my other answer</a>.</p> |
5,877,306 | Remove duplicates in a Django query | <p>Is there a simple way to remove duplicates in the following basic query:</p>
<pre><code>email_list = Emails.objects.order_by('email')
</code></pre>
<p>I tried using <code>duplicate()</code> but it was not working. What is the exact syntax for doing this query without duplicates?</p> | 5,879,542 | 8 | 2 | null | 2011-05-04 00:42:24.233 UTC | 13 | 2022-04-24 21:13:25.897 UTC | 2020-09-13 22:27:29.03 UTC | null | 472,495 | null | 651,174 | null | 1 | 56 | sql|django | 94,833 | <p>This query will not give you duplicates - ie, it will give you all the rows in the database, ordered by email. </p>
<p>However, I presume what you mean is that you have duplicate data within your database. Adding <code>distinct()</code> here won't help, because even if you have only one field, you also have an automatic <code>id</code> field - so the combination of id+email is not unique.</p>
<p>Assuming you only need one field, <code>email_address</code>, de-duplicated, you can do this:</p>
<pre><code>email_list = Email.objects.values_list('email', flat=True).distinct()
</code></pre>
<p>However, you should really fix the root problem, and remove the duplicate data from your database.</p>
<p>Example, deleting duplicate Emails by email field:</p>
<pre><code>for email in Email.objects.values_list('email', flat=True).distinct():
Email.objects.filter(pk__in=Email.objects.filter(email=email).values_list('id', flat=True)[1:]).delete()
</code></pre>
<p>Or books by name:</p>
<pre><code>for name in Book.objects.values_list('name', flat=True).distinct():
Book.objects.filter(pk__in=Artwork.objects.filter(name=name).values_list('id', flat=True)[3:]).delete()
</code></pre> |
6,186,989 | How to change font-color for disabled input? | <p>I need to change the style for a disabled input element in CSS.</p>
<pre class="lang-xml prettyprint-override"><code><input type="text" class="details-dialog" disabled="disabled" />
</code></pre>
<p>How I can do this for Internet Explorer?</p> | 6,187,183 | 11 | 3 | null | 2011-05-31 11:39:32.013 UTC | 14 | 2021-09-03 00:12:52.793 UTC | 2013-06-18 15:09:10.373 UTC | null | 1,281,433 | null | 364,429 | null | 1 | 62 | css|internet-explorer|input | 218,439 | <p>You can't for Internet Explorer.</p>
<p>See <a href="https://stackoverflow.com/questions/5518992/how-can-i-fully-override-chromium-disabled-input-field-colours/#comment-6906168">this comment</a> I wrote on a related topic:</p>
<blockquote>
<p>There doesn't seem to be a good way,
see:
<a href="https://stackoverflow.com/questions/1411044/">How to change color of disabled html controls in IE8 using css</a>
- you can set the input to <code>readonly</code> instead, but that has other
consequences (such as with <code>readonly</code>,
the <code>input</code> will be sent to the server
on submit, but with <code>disabled</code>, it won't
be): <a href="http://jsfiddle.net/wCFBw/40" rel="noreferrer">http://jsfiddle.net/wCFBw/40</a></p>
</blockquote>
<p>Also, see: <a href="https://stackoverflow.com/questions/602070/changing-font-colour-in-textboxes-in-ie-which-are-disabled/602298#602298">Changing font colour in Textboxes in IE which are disabled</a></p> |
55,794,280 | Jest fails with "Unexpected token *" on import statement | <p>Why does <code>Jest</code> fail with "Unexpected token *" on a simple import statement???</p>
<h3>Error log:</h3>
<pre><code>Admin@Admin-PC MINGW32 /d/project (master)
$ npm run test
> [email protected] test D:\project
> jest
FAIL __tests__/App-test.tsx
? Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
D:\project\node_modules\react-navigation-tabs\src\navigators\createBottomTabNavigator.js:3
import * as React from 'react';
^
SyntaxError: Unexpected token *
14 | // );
15 |
> 16 | export default createBottomTabNavigator({
| ^
17 | map: {
18 | screen: MapView,
19 | navigationOptions: {
at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25)
at Object.get createBottomTabNavigator [as createBottomTabNavigator] (node_modules/react-navigation-tabs/src/index.js:9:12)
at Object.<anonymous> (src/app/main.view.tsx:16:16)
FAIL src/component/reinput/example/__tests__/index.ios.js (19.352s)
? Console
console.error node_modules/react-native/Libraries/YellowBox/YellowBox.js:59
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
? renders correctly
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
at invariant (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:55:15)
at createFiberFromTypeAndProps (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:2054:11)
at createFiberFromElement (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:2075:15)
at reconcileSingleElement (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:4605:23)
at reconcileChildFibers (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:4662:35)
at reconcileChildren (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6329:28)
at updateHostRoot (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6741:5)
at beginWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7566:14)
at performUnitOfWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11234:12)
at workLoop (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11266:24)
FAIL src/component/reinput/example/__tests__/index.android.js (19.365s)
? Console
console.error node_modules/react-native/Libraries/YellowBox/YellowBox.js:59
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
? renders correctly
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
at invariant (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:55:15)
at createFiberFromTypeAndProps (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:2054:11)
at createFiberFromElement (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:2075:15)
at reconcileSingleElement (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:4605:23)
at reconcileChildFibers (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:4662:35)
at reconcileChildren (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6329:28)
at updateHostRoot (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6741:5)
at beginWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7566:14)
at performUnitOfWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11234:12)
at workLoop (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11266:24)
Test Suites: 3 failed, 3 total
Tests: 2 failed, 2 total
Snapshots: 0 total
Time: 22.774s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] test: `jest`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Admin\AppData\Roaming\Roaming\npm-cache\_logs\2019-04-22T11_52_36_984Z-debug.log
</code></pre>
<h3><code>package.json</code> file:</h3>
<pre><code>{
"name": "MyApp",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "16.8.3",
"react-native": "0.59.4",
"react-native-gesture-handler": "^1.1.0",
"react-native-reanimated": "^1.0.1",
"react-native-splash-screen": "^3.2.0",
"react-navigation": "^3.8.1",
"react-navigation-tabs": "^2.1.1"
},
"devDependencies": {
"@babel/core": "^7.4.3",
"@babel/runtime": "^7.4.3",
"@types/jest": "^24.0.11",
"@types/react": "^16.8.13",
"@types/react-dom": "^16.8.4",
"@types/react-native": "^0.57.46",
"@types/react-test-renderer": "^16.8.1",
"babel-jest": "^24.7.1",
"jest": "^24.7.1",
"metro-react-native-babel-preset": "^0.53.1",
"react-test-renderer": "16.8.3",
"typescript": "^3.4.3"
},
"jest": {
"preset": "react-native"
}
}
</code></pre>
<h3><code>babel.config.js</code> file:</h3>
<pre><code>module.exports = {
presets: ['module:metro-react-native-babel-preset'],
};
</code></pre>
<h3><code>jest.config.js</code> file:</h3>
<pre><code>module.exports = {
preset: 'react-native',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
}
</code></pre>
<p>Note: I am using <code>react-native</code> type-script template, like <code>react-native init MyApp --template typescript</code></p> | 55,803,188 | 7 | 4 | null | 2019-04-22 12:16:51.373 UTC | 10 | 2022-01-04 14:57:13.66 UTC | 2021-07-12 13:19:46.743 UTC | null | 8,740,349 | null | 8,740,349 | null | 1 | 68 | javascript|typescript|jestjs | 94,507 | <p>Some <code>react-native</code> libraries ship uncompiled ES6 code.</p>
<p>ES6 code needs to be compiled before it can be run by Jest.</p>
<p>The Jest doc about <a href="https://jestjs.io/docs/en/tutorial-react-native" rel="noreferrer">Testing React Native Apps</a> includes a section about <a href="https://jestjs.io/docs/en/tutorial-react-native#transformignorepatterns-customization" rel="noreferrer">compiling dependencies that don't ship pre-compiled code</a>.</p>
<p>You will need to tell Jest to compile <code>react-navigation-tabs</code> by whitelisting it in the <code>transformIgnorePatterns</code> option in your Jest config.</p>
<h2>Example:</h2>
<p>Changing the <code>jest.config.js</code> file into something like below, fixed the issue mentioned in OP.</p>
<p>But the <code>react-native-reanimated</code> module (which requires native integration) needs further work, and we should "Mock" modules with such native requirements (as described in <a href="https://stackoverflow.com/a/53879892/8740349">another post</a>).</p>
<pre class="lang-js prettyprint-override"><code>module.exports = {
preset: 'react-native',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
transformIgnorePatterns: [
"node_modules/(?!(react-native"
+ "|react-navigation-tabs"
+ "|react-native-splash-screen"
+ "|react-native-screens"
+ "|react-native-reanimated"
+ ")/)",
],
}
</code></pre>
<p><strong>Note</strong> that the <code>transformIgnorePatterns</code> option (which is an array of Regular-Expressions) is originally meant to exclude files from being compiled, but using <code>(?!(some-dir-name|another-name))</code> pattern, with the "<code>(?!...)</code>" negative look-ahead, we do tell Jest to exclude anything in <code>node_modules</code> directory, except the names that we did specify.</p> |
9,531,904 | Plot multiple columns on the same graph in R | <p>I have the following data frame:</p>
<pre><code>A B C D Xax
0.451 0.333 0.034 0.173 0.22
0.491 0.270 0.033 0.207 0.34
0.389 0.249 0.084 0.271 0.54
0.425 0.819 0.077 0.281 0.34
0.457 0.429 0.053 0.386 0.53
0.436 0.524 0.049 0.249 0.12
0.423 0.270 0.093 0.279 0.61
0.463 0.315 0.019 0.204 0.23
</code></pre>
<p>I need to plot all these columns in the same plot(on the x-axis I want the variable Xax and the y-axis the variables A,B,C and D) and also to draw the regression line for each variable alone.</p>
<p>I tried this:</p>
<pre><code>pl<-ggplot(data=df) + geom_point(aes(x=Xax,y=A,size=10)) +
geom_point(aes(x=Xax,y=B,size=10)) +
geom_point(aes(x=Xax,y=C,size=10)) +
geom_point(aes(x=Xax,y=D,size=10)) +
geom_smooth(method = "lm", se=FALSE, color="black")
</code></pre>
<p>But it's only plotting the first one(Xax and A)</p> | 9,532,211 | 4 | 0 | null | 2012-03-02 10:41:34.873 UTC | 24 | 2022-01-01 17:36:17.883 UTC | 2022-01-01 17:36:17.883 UTC | null | 1,851,712 | null | 1,187,897 | null | 1 | 50 | r|ggplot2|r-faq | 194,925 | <p>The easiest is to convert your data to a "tall" format.</p>
<pre><code>s <-
"A B C G Xax
0.451 0.333 0.034 0.173 0.22
0.491 0.270 0.033 0.207 0.34
0.389 0.249 0.084 0.271 0.54
0.425 0.819 0.077 0.281 0.34
0.457 0.429 0.053 0.386 0.53
0.436 0.524 0.049 0.249 0.12
0.423 0.270 0.093 0.279 0.61
0.463 0.315 0.019 0.204 0.23
"
d <- read.delim(textConnection(s), sep="")
library(ggplot2)
library(reshape2)
d <- melt(d, id.vars="Xax")
# Everything on the same plot
ggplot(d, aes(Xax,value, col=variable)) +
geom_point() +
stat_smooth()
# Separate plots
ggplot(d, aes(Xax,value)) +
geom_point() +
stat_smooth() +
facet_wrap(~variable)
</code></pre> |
52,205,399 | Percent pie chart with css only | <p>I've found pretty nice "percent pie chart" and want to create it with CSS only. No animation is required. Just static "picture".</p>
<p><img src="https://i.stack.imgur.com/aKkJ3.png" alt="Example 1"></p>
<p>I understand If I wanna create this kind of chart I need to use elements like these</p>
<p><img src="https://i.stack.imgur.com/ARgyS.png" alt="Example 2"></p>
<p>The questions are </p>
<ol>
<li>How to create element #2 ? </li>
<li>How to manage shape of element #2 for smaller (5%) or higher percent (80%) values ?</li>
</ol> | 52,205,730 | 3 | 1 | null | 2018-09-06 13:39:38.037 UTC | 8 | 2021-11-12 08:49:47.49 UTC | 2018-09-06 18:24:02.667 UTC | null | 2,851,632 | null | 10,064,255 | null | 1 | 6 | html|css|charts|pie-chart | 13,190 | <p><strong>New answer 2021</strong></p>
<p>With some modern techniques we can improve the code. You can have rounded edges and also consider animation:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>@property --p{
syntax: '<number>';
inherits: true;
initial-value: 1;
}
.pie {
--p:20; /* the percentage */
--b:22px; /* the thickness */
--c:darkred; /* the color */
--w:150px; /* the size*/
width:var(--w);
aspect-ratio:1/1;
position:relative;
display:inline-grid;
margin:5px;
place-content:center;
font-size:25px;
font-weight:bold;
font-family:sans-serif;
}
.pie:before,
.pie:after {
content:"";
position:absolute;
border-radius:50%;
}
.pie:before {
inset:0;
background:
radial-gradient(farthest-side,var(--c) 98%,#0000) top/var(--b) var(--b) no-repeat,
conic-gradient(var(--c) calc(var(--p)*1%),#0000 0);
-webkit-mask:radial-gradient(farthest-side,#0000 calc(99% - var(--b)),#000 calc(100% - var(--b)));
mask:radial-gradient(farthest-side,#0000 calc(99% - var(--b)),#000 calc(100% - var(--b)));
}
.pie:after {
inset:calc(50% - var(--b)/2);
background:var(--c);
transform:rotate(calc(var(--p)*3.6deg - 90deg)) translate(calc(var(--w)/2 - 50%));
}
.animate {
animation:p 1s .5s both;
}
.no-round:before {
background-size:0 0,auto;
}
.no-round:after {
content:none;
}
@keyframes p{
from{--p:0;}
}
body {
background:#ddd;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="pie" style="--p:20"> 20%</div>
<div class="pie" style="--p:40;--c:darkblue;--b:10px"> 40%</div>
<div class="pie no-round" style="--p:60;--c:purple;--b:15px"> 60%</div>
<div class="pie animate" style="--p:80;--c:orange;"> 80%</div>
<div class="pie animate no-round" style="--p:90;--c:lightgreen"> 90%</div></code></pre>
</div>
</div>
</p>
<p><strong>Old answer</strong></p>
<p>You can do this with multiple background.</p>
<p>From <code>0%</code> to <code>50%</code>:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
width: 100px;
height: 100px;
display: inline-block;
border-radius: 50%;
padding: 5px;
background:
linear-gradient(#ccc, #ccc) content-box,
linear-gradient(var(--v), #f2f2f2 50%, transparent 0),
linear-gradient(to right, #f2f2f2 50%, blue 0);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box" style="--v:-90deg"></div><!-- 0% -->
<div class="box" style="--v:-45deg"></div><!-- 12.5% -->
<div class="box" style="--v: 0deg"></div><!-- 25% -->
<div class="box" style="--v: 45deg"></div><!-- 37.5% -->
<div class="box" style="--v: 90deg"></div><!-- 50% -->
<p>The formula is [p = (18/5) * x - 90]. <small>Where x is the percentage and p the degree</small></p>
<p>for x = 5% --> p = -72deg </p>
<div class="box" style="--v:-72deg"></div></code></pre>
</div>
</div>
</p>
<p>From <code>50%</code> to <code>100%</code>:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
width:100px;
height:100px;
display:inline-block;
border-radius:50%;
padding:5px;
background:
linear-gradient(#ccc,#ccc) content-box,
linear-gradient(var(--v), blue 50%,transparent 0),
linear-gradient(to right, #f2f2f2 50%,blue 0);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box" style="--v:-90deg"></div><!-- 50% -->
<div class="box" style="--v:-45deg"></div><!-- 62.5% -->
<div class="box" style="--v: 0deg"></div><!-- 75% -->
<div class="box" style="--v: 45deg"></div><!-- 87.5% -->
<div class="box" style="--v: 90deg"></div><!-- 100% -->
<p>The formula is [p = (18/5) * x - 270]. <small>Where x is the percentage and p the degree</small></p>
<p>for x = 80% --> p = 18deg </p>
<div class="box" style="--v:18deg"></div></code></pre>
</div>
</div>
</p>
<p>You can combine both like this:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
width:100px;
height:100px;
display:inline-block;
border-radius:50%;
padding:5px;
background:
linear-gradient(#ccc,#ccc) content-box,
linear-gradient(var(--v), #f2f2f2 50%,transparent 0) 0/calc(var(--s)*100%) ,
linear-gradient(var(--v), blue 50%,transparent 0) 0/calc((1 - var(--s))*100%),
linear-gradient(to right, #f2f2f2 50%,blue 0);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box" style="--v:-90deg;--s:1"></div>
<div class="box" style="--v:0deg;--s:1"></div>
<div class="box" style="--v:90deg;--s:1"></div>
<div class="box" style="--v:0deg;--s:0"></div>
<div class="box" style="--v:90deg;--s:0"></div></code></pre>
</div>
</div>
</p>
<p>Now we can optimize like below to consider percetange value:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
--v:calc( ((18/5) * var(--p) - 90)*1deg);
width:100px;
height:100px;
display:inline-block;
border-radius:50%;
padding:10px;
background:
linear-gradient(#ccc,#ccc) content-box,
linear-gradient(var(--v), #f2f2f2 50%,transparent 0) 0/min(100%,(50 - var(--p))*100%),
linear-gradient(var(--v), transparent 50%,blue 0) 0/min(100%,(var(--p) - 50)*100%),
linear-gradient(to right, #f2f2f2 50%,blue 0);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box" style="--p:5;"></div>
<div class="box" style="--p:20;"></div>
<div class="box" style="--p:50;"></div>
<div class="box" style="--p:60;"></div>
<div class="box" style="--p:75;"></div>
<div class="box" style="--p:100;"></div></code></pre>
</div>
</div>
</p>
<p><a href="https://i.stack.imgur.com/PnN47.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PnN47.png" alt="CSS pie chart" /></a></p>
<p>Related question to get another version: <a href="https://stackoverflow.com/q/62924550/8620333">Creating a static pie chart with CSS</a></p>
<hr />
<p>We can also consider <code>mask</code> to add transparency:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
--v:calc( ((18/5) * var(--p) - 90)*1deg);
width:100px;
height:100px;
display:inline-block;
border-radius:50%;
padding:10px;
background:
linear-gradient(var(--v), #f2f2f2 50%,transparent 0) 0/min(100%,(50 - var(--p))*100%),
linear-gradient(var(--v), transparent 50%,blue 0) 0/min(100%,(var(--p) - 50)*100%),
linear-gradient(to right, #f2f2f2 50%,blue 0);
-webkit-mask:
linear-gradient(#fff 0 0) content-box,
linear-gradient(#fff 0 0);
-webkit-mask-composite:destination-out;
mask-composite:exclude;
}
body {
background:linear-gradient(to right,red,yellow);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box" style="--p:5;"></div>
<div class="box" style="--p:20;"></div>
<div class="box" style="--p:50;"></div>
<div class="box" style="--p:60;"></div>
<div class="box" style="--p:75;"></div>
<div class="box" style="--p:100;"></div></code></pre>
</div>
</div>
</p>
<p><a href="https://i.stack.imgur.com/LTS0u.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LTS0u.png" alt="CSS pie chart with transparency" /></a></p>
<p>Also like below:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
--v:calc( ((18/5) * var(--p) - 90)*1deg);
width:100px;
height:100px;
display:inline-block;
border-radius:50%;
padding:10px;
background:
linear-gradient(var(--v), transparent 50%,blue 0) 0/min(100%,(var(--p) - 50)*100%),
linear-gradient(to right, transparent 50%,blue 0);
-webkit-mask:
linear-gradient(var(--v), #f2f2f2 50%,transparent 0) 0/min(100%,(50 - var(--p))*100%),
linear-gradient(#fff 0 0) content-box,
linear-gradient(#fff 0 0);
-webkit-mask-composite:destination-out;
mask-composite:exclude;
}
body {
background:linear-gradient(to right,red,yellow);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box" style="--p:5;"></div>
<div class="box" style="--p:20;"></div>
<div class="box" style="--p:50;"></div>
<div class="box" style="--p:60;"></div>
<div class="box" style="--p:75;"></div>
<div class="box" style="--p:100;"></div></code></pre>
</div>
</div>
</p>
<p><a href="https://i.stack.imgur.com/5oJE2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5oJE2.png" alt="transparent pie chart using CSS mask" /></a></p>
<p>Related: <a href="https://stackoverflow.com/q/51496204/8620333">Border Gradient with Border Radius</a></p> |
47,417,217 | Where to declare variable in react js | <p>I am trying to declare a variable in a react-js class. The variable should be accessible in different functions. This is my code</p>
<pre><code>class MyContainer extends Component {
constructor(props) {
super(props);
this.testVariable= "this is a test"; // I declare the variable here
}
onMove() {
console.log(this.testVariable); //I try to access it here
}
}
</code></pre>
<p>On onMove, the value of <code>this.testVariable</code> is undefined. I Know that I could put the value on the state but I don't want to do it because each time the value changes, <code>render()</code> will be called which is not necessary. I am new to react, did I make something wrong?</p> | 47,417,651 | 2 | 2 | null | 2017-11-21 15:52:54.333 UTC | 25 | 2020-08-16 18:57:44.713 UTC | 2020-08-16 18:57:44.713 UTC | null | 7,462,880 | null | 760,095 | null | 1 | 63 | javascript|reactjs | 199,433 | <p>Using ES6 syntax in React does not bind <code>this</code> to user-defined functions however it will bind <code>this</code> to the component lifecycle methods.</p>
<p>So the function that you declared will not have the same context as the class and trying to access <code>this</code> will not give you what you are expecting.</p>
<p>For getting the context of class you have to bind the context of class to the function or use arrow functions.</p>
<p>Method 1 to bind the context:</p>
<pre><code>class MyContainer extends Component {
constructor(props) {
super(props);
this.onMove = this.onMove.bind(this);
this.testVarible= "this is a test";
}
onMove() {
console.log(this.testVarible);
}
}
</code></pre>
<p>Method 2 to bind the context:</p>
<pre><code>class MyContainer extends Component {
constructor(props) {
super(props);
this.testVarible= "this is a test";
}
onMove = () => {
console.log(this.testVarible);
}
}
</code></pre>
<p><strong>Method 2 is my preferred way</strong> but you are free to choose your own.</p>
<p><strong>Update:</strong> You can also create the properties on class without constructor:</p>
<pre><code>class MyContainer extends Component {
testVarible= "this is a test";
onMove = () => {
console.log(this.testVarible);
}
}
</code></pre>
<p><strong>Note</strong> If you want to update the view as well, you should use <code>state</code> and <code>setState</code> method when you set or change the value.</p>
<p>Example:</p>
<pre><code>class MyContainer extends Component {
state = { testVarible: "this is a test" };
onMove = () => {
console.log(this.state.testVarible);
this.setState({ testVarible: "new value" });
}
}
</code></pre> |
22,906,049 | how to input multiple strings followed by newline | <p>this program asks about how many strings user wants to enter then it takes all strings and stores it.each string is followed by newline which signifies new string is being entered.</p>
<pre><code>#include<stdio.h>
int main()
{
int n,i;
char str[20];
scanf("%d",&n); //how many string
//input each string
for(i=0;i<n;i++)
{
scanf("%s",&str[i]);
}
//display each string
for(i=0;i<n;i++)
{
printf("%s",str[i]);
}
return 0;
}
</code></pre>
<p>there are two problems i'm facing
first whenever i compile and run it in devc++ after taking input of strings program crashes
second i just want to know what i'm doing above is right ?</p> | 22,906,174 | 5 | 1 | null | 2014-04-07 07:28:03.367 UTC | 3 | 2018-11-15 11:46:36.603 UTC | 2014-04-07 07:34:22.367 UTC | null | 3,123,780 | null | 2,760,330 | null | 1 | 3 | c|string | 44,657 | <p>What you want is a 2D character array, which is effectively an array of strings:</p>
<pre><code>#include<stdio.h>
int main()
{
int n,i;
char str[20][20]; // Can store 20 strings, each of length 20
scanf("%d",&n); //how many string
//input each string
for(i=0;i<n;i++)
{
scanf("%s",str[i]);
}
//display each string
for(i=0;i<n;i++)
{
printf("%s",str[i]);
printf("\n");
}
return 0;
}
</code></pre>
<p>The above code runs fine. The changes I have made to your original code are:</p>
<ul>
<li>Declared str as a 2D array of characters, which, as mentioned, is effectively an array of strings.</li>
<li>Removed the & from before str[i]. An & is not needed when scanf is used to read in a string</li>
<li>Added a new line character after each string is printed to make it look more like the input code</li>
</ul> |
23,057,988 | File size exceeds configured limit (2560000), code insight features not available | <p>I am trying to work on a large Javascript file in Jetbrains WebStorm 8 and I am getting a message at the top of the editing window that says:</p>
<blockquote>
<p>File size exceeds configured limit (2560000). Code insight features not available.</p>
</blockquote>
<p>How can I increase the 'configured limit' to get access to all features?</p> | 23,058,324 | 11 | 0 | null | 2014-04-14 10:39:48.51 UTC | 57 | 2022-09-11 21:55:58.16 UTC | 2017-08-31 08:10:24.17 UTC | null | 1,173,112 | null | 692,456 | null | 1 | 300 | intellij-idea | 155,895 | <p>In IntelliJ 2016 and newer you can change this setting from the Help menu, Edit Custom Properties (as commented by @eggplantbr).</p>
<p>On older versions, there's no GUI to do it. But you can change it if you <a href="https://intellij-support.jetbrains.com/hc/en-us/articles/206544869-Configuring-JVM-options-and-platform-properties" rel="noreferrer">edit the IntelliJ IDEA Platform Properties</a> file:</p>
<pre><code>#---------------------------------------------------------------------
# Maximum file size (kilobytes) IDE should provide code assistance for.
# The larger file is the slower its editor works and higher overall system memory requirements are
# if code assistance is enabled. Remove this property or set to very large number if you need
# code assistance for any files available regardless their size.
#---------------------------------------------------------------------
idea.max.intellisense.filesize=2500
</code></pre> |
31,568,351 | How do you configure Embedded MongDB for integration testing in a Spring Boot application? | <p>I have a fairly simple Spring Boot application which exposes a small REST API and retrieves data from an instance of MongoDB. Queries to the MongoDB instance go through a Spring Data based repository. Some key bits of code below.</p>
<pre class="lang-java prettyprint-override"><code>// Main application class
@EnableAutoConfiguration(exclude={MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@ComponentScan
@Import(MongoConfig.class)
public class ProductApplication {
public static void main(String[] args) {
SpringApplication.run(ProductApplication.class, args);
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>// Product repository with Spring data
public interface ProductRepository extends MongoRepository<Product, String> {
Page<Product> findAll(Pageable pageable);
Optional<Product> findByLineNumber(String lineNumber);
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>// Configuration for "live" connections
@Configuration
public class MongoConfig {
@Value("${product.mongo.host}")
private String mongoHost;
@Value("${product.mongo.port}")
private String mongoPort;
@Value("${product.mongo.database}")
private String mongoDatabase;
@Bean(name="mongoClient")
public MongoClient mongoClient() throws IOException {
return new MongoClient(mongoHost, Integer.parseInt(mongoPort));
}
@Autowired
@Bean(name="mongoDbFactory")
public MongoDbFactory mongoDbFactory(MongoClient mongoClient) {
return new SimpleMongoDbFactory(mongoClient, mongoDatabase);
}
@Autowired
@Bean(name="mongoTemplate")
public MongoTemplate mongoTemplate(MongoClient mongoClient) {
return new MongoTemplate(mongoClient, mongoDatabase);
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>@Configuration
@EnableMongoRepositories
public class EmbeddedMongoConfig {
private static final String DB_NAME = "integrationTest";
private static final int DB_PORT = 12345;
private static final String DB_HOST = "localhost";
private static final String DB_COLLECTION = "products";
private MongodExecutable mongodExecutable = null;
@Bean(name="mongoClient")
public MongoClient mongoClient() throws IOException {
// Lots of calls here to de.flapdoodle.embed.mongo code base to
// create an embedded db and insert some JSON data
}
@Autowired
@Bean(name="mongoDbFactory")
public MongoDbFactory mongoDbFactory(MongoClient mongoClient) {
return new SimpleMongoDbFactory(mongoClient, DB_NAME);
}
@Autowired
@Bean(name="mongoTemplate")
public MongoTemplate mongoTemplate(MongoClient mongoClient) {
return new MongoTemplate(mongoClient, DB_NAME);
}
@PreDestroy
public void shutdownEmbeddedMongoDB() {
if (this.mongodExecutable != null) {
this.mongodExecutable.stop();
}
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestProductApplication.class)
@IntegrationTest
@WebAppConfiguration
public class WtrProductApplicationTests {
@Test
public void contextLoads() {
// Tests empty for now
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>@EnableAutoConfiguration(exclude={MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@ComponentScan
@Import(EmbeddedMongoConfig.class)
public class TestProductApplication {
public static void main(String[] args) {
SpringApplication.run(TestProductApplication.class, args);
}
}
</code></pre>
<p>So the idea here is to have the integration tests (empty at the moment) connect to the embedded mongo instance and not the "live" one. However, it doesn't work. I can see the tests connecting to the "live" instance of Mongo, and if I shut that down the build simply fails as it is still attempting to connect to the live instance of Mongo. Does anyone know why this is? How do I get the tests to connect to the embedded instance?</p> | 31,568,654 | 5 | 2 | null | 2015-07-22 16:03:33.373 UTC | 9 | 2019-01-03 14:08:06.323 UTC | null | null | null | null | 128,285 | null | 1 | 36 | java|spring|mongodb|spring-boot | 69,862 | <p><strong>EDIT</strong>: see <a href="https://stackoverflow.com/a/35204466/1967100">magiccrafter's answer</a> for Spring Boot 1.3+, using <code>EmbeddedMongoAutoConfiguration</code>.</p>
<p>If you can't use it for any reason, keep reading.</p>
<hr>
<p>Test class:</p>
<pre><code> @RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {
Application.class,
TestMongoConfig.class // <--- Don't forget THIS
})
public class GameRepositoryTest {
@Autowired
private GameRepository gameRepository;
@Test
public void shouldCreateGame() {
Game game = new Game(null, "Far Cry 3");
Game gameCreated = gameRepository.save(game);
assertEquals(gameCreated.getGameId(), gameCreated.getGameId());
assertEquals(game.getName(), gameCreated.getName());
}
}
</code></pre>
<p>Simple MongoDB repository:</p>
<pre><code>public interface GameRepository extends MongoRepository<Game, String> {
Game findByName(String name);
}
</code></pre>
<p>MongoDB test configuration:</p>
<pre><code>import com.mongodb.Mongo;
import com.mongodb.MongoClientOptions;
import de.flapdoodle.embed.mongo.MongodExecutable;
import de.flapdoodle.embed.mongo.MongodProcess;
import de.flapdoodle.embed.mongo.MongodStarter;
import de.flapdoodle.embed.mongo.config.IMongodConfig;
import de.flapdoodle.embed.mongo.config.MongodConfigBuilder;
import de.flapdoodle.embed.mongo.config.Net;
import de.flapdoodle.embed.mongo.distribution.Version;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
@Configuration
public class TestMongoConfig {
@Autowired
private MongoProperties properties;
@Autowired(required = false)
private MongoClientOptions options;
@Bean(destroyMethod = "close")
public Mongo mongo(MongodProcess mongodProcess) throws IOException {
Net net = mongodProcess.getConfig().net();
properties.setHost(net.getServerAddress().getHostName());
properties.setPort(net.getPort());
return properties.createMongoClient(this.options);
}
@Bean(destroyMethod = "stop")
public MongodProcess mongodProcess(MongodExecutable mongodExecutable) throws IOException {
return mongodExecutable.start();
}
@Bean(destroyMethod = "stop")
public MongodExecutable mongodExecutable(MongodStarter mongodStarter, IMongodConfig iMongodConfig) throws IOException {
return mongodStarter.prepare(iMongodConfig);
}
@Bean
public IMongodConfig mongodConfig() throws IOException {
return new MongodConfigBuilder().version(Version.Main.PRODUCTION).build();
}
@Bean
public MongodStarter mongodStarter() {
return MongodStarter.getDefaultInstance();
}
}
</code></pre>
<p>pom.xml</p>
<pre><code> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<version>1.48.0</version>
<scope>test</scope>
</dependency>
</code></pre> |
19,046,812 | Multiple COUNT() for multiple conditions in one query (MySQL) | <p>I have these queries :</p>
<pre><code>SELECT COUNT(*) FROM t_table WHERE color = 'YELLOW';
SELECT COUNT(*) FROM t_table WHERE color = 'BLUE';
SELECT COUNT(*) FROM t_table WHERE color = 'RED';
</code></pre>
<p>Is there any way to get these results in one query?</p> | 19,046,871 | 7 | 1 | null | 2013-09-27 09:03:12.36 UTC | 9 | 2022-09-06 16:52:14.737 UTC | 2015-03-09 09:32:18.03 UTC | null | 2,747,408 | null | 2,747,408 | null | 1 | 37 | mysql|sql|count | 101,163 | <pre><code>SELECT color, COUNT(*) FROM t_table GROUP BY color
</code></pre> |
18,962,953 | Google Spreadsheet sum which always ends on the cell above | <p>How to create a Google Spreadsheet sum() which always ends on the cell above, even when new cells are added? I have several such calculations to make on each single column so <a href="https://stackoverflow.com/questions/12223180/google-spreadsheet-sum-of-row-n-through-last-row">solutions like this</a> won't help.</p>
<p>Example: </p>
<blockquote>
<p>On column B, I have several dynamic ranges which has to be summed. B1..B9 should be summed on B10, and B11..B19 should be summed on B20. I have tens such calculations to make. Every now and then, I add rows below the last summed row , and I want them to be added to the sum. I add a new row (call it 9.1) before row 10, and a new raw (let's call it 19.1) before row 20. I want B10 to contain the sum of B1 through B9.1 and B20 to contain the sum of B11:B19.1. </p>
</blockquote>
<p>On excel, I have the <a href="http://spreadsheets.about.com/od/excelslookupfunctions/ss/2013-04-20-excel-sum-offset-formula-tutorial.htm" rel="noreferrer">offset function</a> which does it like charm. But how to do it with google spreadsheet? I tried to use formulas like this:</p>
<pre><code>=SUM(B1:INDIRECT(address(row()-1,column(),false))) # Formula on B10
=SUM(B11:INDIRECT(address(row()-1,column(),false))) # Formula on B20
</code></pre>
<p>But on Google Spreadsheet, all it gives is a #name error.</p>
<p>I wasted hours trying to find a solution, maybe someone can calp?
Please advise</p>
<p>Amnon</p> | 18,986,542 | 10 | 1 | null | 2013-09-23 15:19:02.093 UTC | 16 | 2022-04-12 15:09:39.26 UTC | 2017-05-23 10:31:30.497 UTC | null | -1 | null | 1,780,816 | null | 1 | 48 | google-sheets | 56,061 | <p>You are probably looking for formula like:</p>
<p><code>=SUM(INDIRECT("B1:"&ADDRESS(ROW()-1,COLUMN(),4)))</code></p>
<p>Google Spreadsheet INDIRECT returns reference to a cell or <strong>area</strong>, while - from what I recall - Excel INDIRECT returns always reference to a cell.
Given Google's INDIRECT indeed has some hard time when you try to use it inside SUM as cell reference, what you want is to feed SUM with whole range to be summed up in e.g. a1 notation: "B1:BX". </p>
<p>You get the address you want in the same way as in EXCEL (note "4" here for row/column relative, by default Google INDIRECT returns absolute):</p>
<p><code>ADDRESS(ROW()-1,COLUMN(),4)</code> </p>
<p>and than use it to prepare range string for SUM function by concatenating with starting cell.</p>
<p><code>"B1:"&</code></p>
<p>and wrap it up with INDIRECT, which will return area to be sum up.</p>
<p><strong>REFERRING TO BELOW ANSWER from Druvision (I cant comment yet, I didn't want to multiply answers)</strong></p>
<p>Instead of time consuming formulas corrections each time row is inserted/deleted to make all look like:</p>
<p><code>=SUM(INDIRECT(ADDRESS(ROW()-9,COLUMN(),4)&":"&ADDRESS(ROW()-1,COLUMN(),4)))</code></p>
<p>You can spare one column in separate sheet for holding variables (let's name it "def"), let's say Z, to define starting points e.g.
in Z1 write "B1"
in Z2 write "B11"
etc.
and than use it as variable in your sum by using INDEX:</p>
<p><code>SUM(INDIRECT(INDEX(def!Z:Z,1,1)&":"&ADDRESS(ROW()-1,COLUMN(),4)))</code> - sums from B1 to calculated row, since in Z1 we have "B1" ( the <code>1,1</code> in <code>INDEX(...,1,1)</code> )</p>
<p><code>SUM(INDIRECT(INDEX(def!Z:Z,2,1)&":"&ADDRESS(ROW()-1,COLUMN(),4)))</code> - sums from B11 to calculated row, since in Z2 we have "B11" ( the <code>2,1</code> in <code>INDEX(...,2,1)</code> )</p>
<p>please note:</p>
<ol>
<li><p>Separate sheet named 'def' - you don't want row insert/delete influence that data, thus keep it on side. Useful for adding some validation lists, other stuff you need in your formulas.</p></li>
<li><p>"Z:Z" notation - whole column. You said you had a lot of such formulas ;)</p></li>
</ol>
<p>Thus you preserve flexibility of defining starting cell for each of your formulas, which is not influenced by calculation sheet changes.</p>
<p>By the way, wouldn't it be easier to write custom function/script summing up all rows above cell? If you feel like javascripting, from what I recall, google spreadsheet has now nice script editor. You can make a function called e.g. <em>sumRowsAboveMe()</em> and than just use it in your sheet like <code>=sumRowsAboveMe()</code> in sheet cell.</p>
<p><strong>Note: you might have to <a href="https://webapps.stackexchange.com/questions/99938/google-sheets-documentation-falsely-using-commas-to-separate-parameters">replace commas by semicolons</a></strong> </p> |
18,114,343 | How does zmq poller work? | <p>I am confused as to what poller actually does in zmq. The zguide goes into it minimally, and only describes it as a way to read from multiple sockets. This is not a satisfying answer for me because it does not explain how to have timeout sockets. I know <a href="https://stackoverflow.com/questions/7538988/zeromq-how-to-prevent-infinite-wait">zeromq: how to prevent infinite wait?</a> explains for push/pull, but not req/rep patterns, which is what I want to know how to use.</p>
<p>What I am attempting to ask is: How does poller work, and how does its function apply to keeping track of sockets and their requests?</p> | 18,116,839 | 2 | 1 | null | 2013-08-07 21:42:21.847 UTC | 25 | 2021-05-25 15:57:04.497 UTC | 2017-05-23 12:25:17.053 UTC | null | -1 | null | 1,876,508 | null | 1 | 55 | sockets|zeromq | 31,295 | <p>When you need to listen on different sockets in the same thread, use a poller:</p>
<pre><code>ZMQ.Socket subscriber = ctx.socket(ZMQ.SUB)
ZMQ.Socket puller = ctx.socket(ZMQ.PULL)
</code></pre>
<p>Register sockets with poller (<code>POLLIN</code> listens for incoming messages)</p>
<pre><code>ZMQ.Poller poller = ZMQ.Poller(2)
poller.register(subscriber, ZMQ.Poller.POLLIN)
poller.register(puller, ZMQ.Poller.POLLIN)
</code></pre>
<p>When polling, use a loop:</p>
<pre><code>while( notInterrupted()){
poller.poll()
//subscriber registered at index '0'
if( poller.pollin(0))
subscriber.recv(ZMQ.DONTWAIT)
//puller registered at index '1'
if( poller.pollin(1))
puller.recv( ZMQ.DONTWAIT)
}
</code></pre>
<p>Choose how you want to poll...</p>
<p><code>poller.poll()</code> blocks until there's data on either socket.<br>
<code>poller.poll(1000)</code> blocks for 1s, then times out.</p>
<p>The poller notifies when there's data (messages) available on the sockets; it's your job to read it.</p>
<p>When reading, do it without blocking: <code>socket.recv( ZMQ.DONTWAIT)</code>. Even though <code>poller.pollin(0)</code> checks if there's data to be read, you want to avoid any blocking calls inside the polling loop, otherwise, you could end up blocking the poller due to 'stuck' socket.</p>
<p>So, if two separate messages are sent to <code>subscriber</code>, you have to invoke <code>subscriber.recv()</code> twice in order to clear the poller, otherwise, if you call <code>subscriber.recv()</code> once, the poller will keep telling you there's another message to be read. So, in essence, the poller tracks the availability and number of messages, not the actual messages.</p>
<p>You should run through the polling examples and play with the code, it's the best way to learn.</p>
<p>Does that answer your question?</p> |
3,311,225 | CouchDB sorting and filtering in the same view | <p>I'm trying to use CouchDB for a new app, and I need to create a view that sorts by multiple fields and also filters by multiple fields. Here is an example document, I've left out the _id and _rev to save myself some typing.</p>
<pre><code>{
"title": "My Document",
"date": 1279816057,
"ranking": 5,
"category": "fun",
"tags": [
"couchdb",
"technology"
],
}
</code></pre>
<p>From the documentation, I've learned that I can easily create a view that sorts by a field such as ranking.</p>
<pre><code>function(doc) {
emit(doc.ranking, doc);
}
</code></pre>
<p>I've also learned that I can easily filter by fields such as category</p>
<pre><code>function(doc) {
emit(doc.category, doc);
}
http://127.0.0.1:5984/database/_design/filter/_view/filter?key=%22fun%22
</code></pre>
<p>My problem is that I need to do a bunch of these things all at the same time. I want to filter based on category and also tag. I should be able to filter down to only documents with category of "fun" and tag of "couchdb". I want to sort those filtered results by ranking in descending order, then by date in ascending order, then by title in alphabetical order. </p>
<p>How can I create one view that does all of that sorting and filtering combined?</p> | 3,313,336 | 1 | 0 | null | 2010-07-22 16:46:02.883 UTC | 22 | 2017-05-11 15:26:50.317 UTC | null | null | null | null | 65,326 | null | 1 | 34 | sorting|filter|nosql|couchdb | 24,163 | <p>For emitting more than one piece of data in a key, you'll want to read up on <a href="http://wiki.apache.org/couchdb/View_collation" rel="noreferrer">Complex Keys</a>. You'll most likely end up <code>emit()</code>'ing a key that is an array made up of the category and tag. For example...</p>
<pre><code>function(doc) {
for(var i = 0; i < doc.tags.length; i++)
emit([doc.category, doc.tags[i]], doc);
}
</code></pre>
<p>Now when you query <code>?key=["fun", "couchdb"]</code> you'll get all the items in the fun category tagged with "couchdb". Or if you want all of the items in the fun category, regardless of their tag, then you can query with a range: <code>?startkey=["fun"]&endkey=["fun", {}]</code>. Just remember, if your item has multiple tags, you'll get it multiple times in the results (because you <code>emit()</code>'d the doc once per tag).</p>
<p>To go the extra step of sorting by rating, date, and title you'll add two more elements to your array: an integer and either the ranking, date, or title. Remember, you can <code>emit()</code> more than once per map function. An example map function...</p>
<pre><code>function(doc) {
for(var i = 0; i < doc.tags.length; i++)
{
emit([doc.category, doc.tags[i], 0, doc.ranking], doc);
emit([doc.category, doc.tags[i], 1, doc.title], doc);
emit([doc.category, doc.tags[i], 2, doc.date], doc);
}
}
</code></pre>
<p>Now your key structure is: <code>["category", "tag", 0 ... 2, rank/title/date]</code></p>
<p>You're basically grouping all of the rankings under 0, titles under 1, and dates under 2. Of course, you're transmitting a lot of data, so you could either break each of these groupings out into a separate view in your design document, or only return the doc's <code>_id</code> as the value (<code>emit([ ...], doc._id);</code>). </p>
<p>Get everything in the "fun" category with the "couchdb" tag (ascending):</p>
<pre><code>?startkey=["fun", "couchdb"]&endkey=["fun", "couchdb", {}, {}]
</code></pre>
<p>Get everything in the "fun" category with the "couchdb" tag (descending):</p>
<pre><code>?startkey=["fun", "couchdb", {}, {}]&endkey=["fun", "couchdb"]&descending=true
</code></pre>
<p>Get only rankings in the fun category with the couchdb tag (ascending):</p>
<p><code>?startkey=["fun", "couchdb", 0]&endkey=["fun", "couchdb", 0, {}]</code></p>
<p>Get only rankings in the "fun" category with the "couchdb" tag (descending):</p>
<pre><code>?startkey=["fun", "couchdb", 0, {}]&endkey=["fun", "couchdb", 0]&descending=true
</code></pre>
<p>I hope this helps. Complex keys start to really show how powerful Map/Reduce is at slicing and dicing data.</p>
<p>Cheers.</p> |
28,238,161 | How to make an asynchronous Dart call synchronous? | <p>I'm on the way to evaluate Dart for a German company by porting various Java programs to Dart and compare and analyze the results. In the browser Dart wins hands down. For server software performance seemed to be a serious isssue (see <a href="https://stackoverflow.com/questions/28026648/how-to-improve-dart-performance-of-data-conversion-to-from-binary">this question of me</a>) but that got mostly defused.</p>
<p>Now I'm in the area of porting some "simple" command-line tools where I did not expect any serious problems at all but there is at least one. Some of the tools do make HTTP requests to collect some data and the stand-alone Dart virtual machine only supports them in an asynchronous fashion. Looking through all I could find it does not seem to be possible to use any asynchronous call in a mostly synchronous software.</p>
<p>I understand that I could restructure the available synchronous software into an asynchronous one. But this would transform a well-designed piece of software into something less readable and more difficult to debug and maintain. For some software pieces this just does not make sense.
My question: Is there an (overlooked by me) way to embed an asynchronous call into a synchronously called method?</p>
<p>I imagine that it would not be to difficult to provide a system call, usable only from within the main thread, which just transfers the execution to the whole list of queued asynchronous function calls (without having to end the main thread first) and as soon as the last one got executed returns and continues the main thread.</p>
<p>Something which might look like this:</p>
<pre class="lang-dart prettyprint-override"><code>var synchFunction() {
var result;
asyncFunction().then(() { result = ...; });
resync(); // the system call to move to and wait out all async execution
return result;
}
</code></pre>
<p>Having such a method would simplify the lib APIs as well. Most "sync" calls could be removed because the re-synchronisation call would do the job. It seems to be such a logical idea that I still think it somehow exists and I have missed it. Or is there a serious reason why that would not work?
<hr>
After thinking about the received answer from <code>lm</code> (see below) for two days I still do not understand why the encapsulation of an asynchronous Dart call into a synchronous one should not be possible. It is done in the "normal" synchronous programing world all the time. Usually you can wait for a resynchronization by either getting a "Done" from the asynchronous routine or if something fails continue after a timeout.</p>
<p>With that in mind my first proposal could be enhanced like that:
</p>
<pre class="lang-dart prettyprint-override"><code>var synchFunction() {
var result;
asyncFunction()
.then(() { result = ...; })
.whenComplete(() { continueResync() }); // the "Done" message
resync(timeout); // waiting with a timeout as maximum limit
// Either we arrive here with the [result] filled in or a with a [TimeoutException].
return result;
}
</code></pre>
<p>The <code>resync()</code> does the same that would normally happen after ending the <code>main</code> method of an isolate, it starts executing the queued asynchronous functions (or waits for events to make them executable). As soon as it encounters a <code>continueResync()</code> call a flag is set which stops this asynchronous execution and <code>resync()</code> returns to the main thread. If no <code>continueResync()</code> call is encountered during the given <code>timeout</code> period it too aborts the asynchronous execution and leaves <code>resync()</code> with a <code>TimeoutException</code>.</p>
<p>For some groups of software which benefit from straight synchronous programing (not the client software and not the server software) such a feature would solve lots of problems for the programer who has to deal with asynchrounous-only libraries.</p>
<p>I believe that I have also found a solution for the main argument in <code>lm</code>'s argumentation below. Therefore my question still stands with respect to this "enhanced" solution which I proposed: <strong>Is there anything which really makes it impossible to implement that in Dart?</strong></p> | 41,401,506 | 8 | 1 | null | 2015-01-30 14:35:53.047 UTC | 11 | 2022-09-13 22:22:14.767 UTC | 2017-05-23 12:10:43.367 UTC | null | -1 | null | 2,862,220 | null | 1 | 44 | asynchronous|dart|synchronous | 47,029 | <p>The only time that you can wrap an async method in a synchronous one is when you don't need to get a return value.</p>
<p>For example if you want to disable the save button, save results to the server asynchronously and re-enable the save button when the job is done you can write it like this:</p>
<pre><code>Future<bool> save() async {
// save changes async here
return true;
}
void saveClicked() {
saveButton.enabled = false;
save()
.then((success) => window.alert(success ? 'Saved' : 'Failed'))
.catchError((e) => window.alert(e))
.whenComplete(() { saveButton.enabled = true; });
}
</code></pre>
<p>Note that the <code>saveClicked</code> method is fully synchronous, but executes the <code>save</code> method asynchronously.</p>
<p>Note that if you make <code>saveClicked</code> async, not only do you have to call it using the async pattern, but the entire method body will run asynchronously so the save button will not be disabled when the function returns.</p>
<p>For completeness the async version of <code>saveClicked</code> looks like this:</p>
<pre><code>Future<Null> saveClicked() async {
saveButton.enabled = false;
try {
bool success = await save();
window.alert(success ? 'Saved' : 'Failed');
}
catch (e) {
window.alert(e);
}
finally {
saveButton.enabled = true;
}
}
</code></pre> |
28,058,278 | How do I reverse a slice in go? | <p>How do I reverse an arbitrary slice (<code>[]interface{}</code>) in Go? I'd rather not have to write <code>Less</code> and <code>Swap</code> to use <code>sort.Reverse</code>. Is there a simple, builtin way to do this?</p> | 28,058,324 | 5 | 2 | null | 2015-01-21 01:47:23.567 UTC | 6 | 2022-06-22 08:58:11.883 UTC | 2022-06-22 08:55:22.067 UTC | null | 9,935,654 | null | 454,196 | null | 1 | 39 | go|slice | 38,434 | <p>The standard library does not have a built-in function for reversing a slice. Use a for loop to reverse a slice:</p>
<pre><code>for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
</code></pre>
<p>Use type parameters to write a generic reverse function in Go 1.18 or later:</p>
<pre><code>func reverse[S ~[]E, E any](s S) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}
</code></pre>
<p>Use <a href="https://pkg.go.dev/reflect#Swapper" rel="noreferrer">reflect.Swapper</a> to write a function that works with arbitrary slice types in Go version 1.8 or later:</p>
<pre><code>func reverse(s interface{}) {
n := reflect.ValueOf(s).Len()
swap := reflect.Swapper(s)
for i, j := 0, n-1; i < j; i, j = i+1, j-1 {
swap(i, j)
}
}
</code></pre>
<p><a href="https://gotipplay.golang.org/p/q0hXFLyBuGj" rel="noreferrer">Run the code on the Go playground</a>.</p>
<p>The functions in this answer reverse the slice inplace. If you do not want to modify the original slice, <a href="https://github.com/golang/go/wiki/SliceTricks#copy" rel="noreferrer">copy the slice</a> before reversing the slice.</p> |
1,955,048 | Get computed font size for DOM element in JS | <p>Is it possible to detect the computed <code>font-size</code> of a DOM element, taking into consideration generic settings made elsewhere (In the <code>body</code> tag for example), inherited values, and so on? </p>
<p>A framework-independent approach would be nice, as I'm working on a script that should work standalone, but that is not a requirement of course.</p>
<p>Background: I'm trying to tweak <a href="http://ckeditor.com/" rel="noreferrer">CKEditor's</a> font selector plugin (source <a href="http://svn.fckeditor.net/CKEditor/releases/stable/_source/plugins/font/plugin.js" rel="noreferrer">here</a>) so that it always shows the font size of the current cursor position (as opposed to only when within a <code>span</code> that has an explicit <code>font-size</code> set, which is the current behaviour).</p> | 1,955,160 | 3 | 3 | null | 2009-12-23 20:13:10.483 UTC | 18 | 2013-04-11 03:12:27.11 UTC | 2010-04-28 17:17:24.767 UTC | null | 187,606 | null | 187,606 | null | 1 | 36 | javascript|jquery|css|ckeditor|font-size | 23,590 | <p>You could try to use the non-standard IE <a href="http://msdn.microsoft.com/en-us/library/ms535231(VS.85).aspx" rel="noreferrer"><code>element.currentStyle</code></a> property, otherwise you can look for the <a href="http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSview-getComputedStyle" rel="noreferrer">DOM Level 2</a> standard <a href="https://developer.mozilla.org/en/DOM/window.getComputedStyle" rel="noreferrer"><code>getComputedStyle</code></a> method if available :</p>
<pre><code>function getStyle(el,styleProp) {
var camelize = function (str) {
return str.replace(/\-(\w)/g, function(str, letter){
return letter.toUpperCase();
});
};
if (el.currentStyle) {
return el.currentStyle[camelize(styleProp)];
} else if (document.defaultView && document.defaultView.getComputedStyle) {
return document.defaultView.getComputedStyle(el,null)
.getPropertyValue(styleProp);
} else {
return el.style[camelize(styleProp)];
}
}
</code></pre>
<p>Usage:</p>
<pre><code>var element = document.getElementById('elementId');
getStyle(element, 'font-size');
</code></pre>
<p>More info:</p>
<ul>
<li><a href="http://www.quirksmode.org/dom/getstyles.html" rel="noreferrer">Get Styles</a> (QuirksMode)</li>
</ul>
<p><strong>Edit:</strong> Thanks to <em>@Crescent Fresh</em>, <em>@kangax</em> and <em>@Pekka</em> for the comments.</p>
<p>Changes:</p>
<ul>
<li>Added <code>camelize</code> function, since properties containing hypens, like <code>font-size</code>, must be accessed as camelCase (eg.: <code>fontSize</code>) on the <code>currentStyle</code> IE object.</li>
<li>Checking the existence of <code>document.defaultView</code> before accessing <code>getComputedStyle</code>.</li>
<li>Added last case, when <code>el.currentStyle</code> and <code>getComputedStyle</code> are not available, get the inline CSS property via <code>element.style</code>.</li>
</ul> |
27,022,167 | Generic CRUD controllers and views | <p>I'm just going through some intro tutorials for ASP.NET and I've got a decent idea of how to implement a simple CRUD admin app.</p>
<p>Are there any commonly used patterns to implement generic List/Create/Update/Delete actions? It seems pretty tedious to have to build scaffolding for every model, and then to maintain all of the add, edit and list views and controllers. It would be a lot more efficient and less error-prone to implement generic actions like:</p>
<pre><code>/List/Model
/Edit/Model/id
/Update/Model/id
/Delete/Model/id
</code></pre>
<p>that would handle any model.</p> | 27,024,264 | 1 | 2 | null | 2014-11-19 16:39:31.87 UTC | 11 | 2014-11-19 18:29:29.387 UTC | null | null | null | null | 2,871,709 | null | 1 | 9 | asp.net-mvc | 5,571 | <p>I've done something similar, I think, to what you're talking about in an admin application I built. Basically, the key is to use generics. In other words, you create a controller like:</p>
<pre><code>public abstract class AdminController<TEntity> : Controller
where TEntity : IEntity, class, new()
{
protected readonly ApplicationDbContext context;
public virtual ActionResult Index()
{
var entities = context.Set<TEntity>()
return View(entities);
}
public virtual ActionResult Create()
{
var entity = new TEntity();
return View(entity);
}
[HttpPost]
public virtual ActionResult Create(TEntity entity)
{
if (ModelState.IsValid)
{
context.Set<TEntity>().Add(entity);
context.SaveChanges();
return RedirectToAction("Index");
}
return View(entity);
}
...
}
</code></pre>
<p>In other words, you just build an entire reusable controller structure, with the key parts being that you're using the generic <code>TEntity</code> instead of a concrete class. Notice that <code>TEntity</code> is defined as <code>IEntity, class, new()</code>. This does a few things. First, <code>class</code> allows you to treat it as a concrete type and <code>new()</code> means that the type will be something that can be instantiated, rather than something like an abstract class. <code>IEntity</code> is just a placeholder for whatever you may be using in your application to ensure all the types have some common denominator. At the very least for a CRUD-style application, you'll need this to gain access to an <code>Id</code> or similar property for things like your edit and delete actions. Saying that <code>TEntity</code> implements <code>IEntity</code> lets you utilize any properties on <code>IEntity</code>. If you use a concrete type here instead of an interface, you can leave off the <code>class</code> part, e.g. <code>where TEntity : Entity, new()</code>.</p>
<p>Then, in order to use this, you just define a new controller that inherits from <code>AdminController<></code> and specify the type you're working with:</p>
<pre><code>public class WidgetController : AdminController<Widget>
{
public WidgetController(ApplicationDbContext context)
{
this.context = context;
}
}
</code></pre>
<p>That could be potentially all you need for your individual controllers. Also, worth noting here is that I've set this up to employ dependency injection for your context. You could always change your constructor to something like:</p>
<pre><code>public WidgetController()
{
this.context = new ApplicationDbContext();
}
</code></pre>
<p>But, I recommend you do look into using dependency injection, in general. Also, I'm using the context directly here for ease of explanation, but usually you'd be employing services, repositories, etc. here instead.</p>
<p>Finally, if you find you need to customize certain parts of a CRUD action, but not necessarily the whole thing, you can always add methods as extension points. For example, let's say you needed to populate a select list for one particular entity, you might do something like:</p>
<pre><code>public abstract class AdminController<TEntity> : Controller
where TEntity : IEntity, class, new()
{
...
public virtual ActionResult Create()
{
var entity = new TEntity();
BeforeReturnView();
return View(entity);
}
...
protected virtual void BeforeReturnView()
{
}
...
</code></pre>
<p>And then:</p>
<pre><code>public class WidgetController : AdminController<Widget>
{
...
protected override void BeforeReturnView()
{
ViewBag.MySelectList = new List<SelectListItem>
{
...
};
}
}
</code></pre>
<p>In other words, you have a hook in your base action method that you override to just change that particular bit of functionality instead of having to override the whole action itself.</p>
<p>You can also take this farther to include things like view models, where you might expand your generic class definition to something like:</p>
<pre><code> public abstract class AdminController<TEntity, TEntityViewModel, TEntityCreateViewModel, TEntityUpdateViewModel>
where TEntity : IEntity, class, new()
where TEntityViewModel : class, new()
...
</code></pre>
<p>And then:</p>
<pre><code>public class WidgetController : AdminController<Widget, WidgetViewModel, WidgetCreateViewModel, WidgetUpdateViewModel>
{
...
}
</code></pre>
<p>It all depends on what your application needs.</p> |
1,311,494 | Step by step process for CSS/HTML layout? | <p>I'm a sometime developer who is trying to get up to speed on customer-facing sites. I have a designer (who has years of experience, but it's all been print, so she's also ramping up on web design) so I'm not looking for design or usability tips. What I am interested in hearing about is the step-by-step process of doing the actual coding for a page. I want to make sure I get off on the right foot and build the pieces up in a logical order.</p>
<p>So please share your thoughts on what things you generally do first, second, etc. in your style sheets and HTML. I mean after you already have mockups (in Photoshop, or whatever) and are sitting down to create your code.</p>
<p>For example, do you first think about all the sections on your page (header, nav bar, content, rss feeds), and then add appropriate DIVs to your style sheet? And then go in and work on each section in detail?</p>
<p>(I know there have been other posts for web design tips/best practices, but I haven't found any that focus on the step-by-step coding process.)</p>
<p>Thanks!</p> | 1,311,552 | 4 | 1 | null | 2009-08-21 11:49:00.673 UTC | 11 | 2009-08-21 13:32:41.983 UTC | null | null | null | null | 115,961 | null | 1 | 6 | html|css | 3,651 | <p>Here is the correct way to do this by the numbers:</p>
<p>1) Write your HTML. Do not do anything but write it. Do not render it in a browser to see what it looks like most importantly. Focus on semantics, brevity, and accessibility. At this point nothing else matters. If you get this step wrong nothing else will matter.</p>
<p>2) Validate your HTML. If your HTML fails validation then fix it before doing anything else.</p>
<p>3) Write CSS for your HTML. At this point your will have to render your HTML in a browser to see the impacts of your CSS. Do not make changes to the structure of your HTML to fit the demands of presentation. That is why you write your HTML first. The only things you should be altering in your HTML at this point are the class, id, and title attributes of your tags. CSS is referenced from the head section of the HTML using a link tag with an attribute of rel="stylesheet". Do not attempt to include a stylesheet using a style tag or the @import rule.</p>
<p>4) After the CSS is complete and everything looks pretty then create any background images required of the CSS.</p>
<p>5) Only after the CSS and everything required from the CSS is complete should you work on JavaScript. JavaScript does not ever go into your HTML. JavaScript always goes into an external js file. JavaScript is referenced by use a script tag that occurs directly prior to the closing body tag only.</p>
<p>6) Upon completion of your JavaScript pass it through the JSLint tool. Rewrite your JavaScript exactly like it says.</p>
<p>When I have worked with designers that have migrated from print to web I have encountered problems. Print designers typically fail to leave the print world behind when they attempt to adapt their experience of layout to the web. The web is not print. Print has different limitations and freedoms than does the web. Even grid layouts sometimes do not fail to convert from print to web design.</p> |
1,332,691 | How to configure logs/catalina.out of tomcat 6 for per-app. (Configure web-app specific log file for sys.out, sys.err) | <p>Requirement is this ...</p>
<p>We have our 3 web-applications deployed in RHEL-5 server, we deployed apps with tomcat 6.0.16.
We want to configure stdout, stderr, which are coming in tomcat/logs/catalina.out in app specific log file like, </p>
<p>tomcat/logs/app1.log
tomcat/logs/app2.log
tomcat/logs/app3.log</p>
<p>we are using log4j, but it is only generating logging details we need stdout per-app which is coming in tomcat/logs/catalina.out</p>
<p>Any Help Appreciated ...</p> | 1,338,524 | 1 | 0 | null | 2009-08-26 06:25:46.537 UTC | 15 | 2016-08-01 09:02:04.49 UTC | 2009-08-26 09:59:24.75 UTC | null | 104,024 | null | 104,024 | null | 1 | 28 | tomcat|logging|log4j|stdout | 55,804 | <p>Try this,</p>
<ol>
<li>Each application must use its own log4j. You can achieve this by placing log4j.jar in WEB-INF/lib of each application.</li>
<li>In each log4j's configuration file (default location is WEB-INF/classes), specify the log file name, e.g. <code>log4j.appender.AppLog.File=${catalina.home}/logs/app1.log</code>.</li>
<li>Add <code>swallowOutput="true"</code> for each context so stdout, stderr will go to your own log.</li>
</ol>
<p>We do this on Tomcat 5.5 but I think it should work on 6.0 also.</p>
<p>EDIT: Here is our META-INF/context.xml,</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<Context override="true" swallowOutput="true" useNaming="false">
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Manager pathname=""/>
</Context>
</code></pre> |
2,969,044 | Python "string_escape" vs "unicode_escape" | <p><a href="https://docs.python.org/2.7/library/codecs.html#python-specific-encodings" rel="nofollow noreferrer">According to the docs</a>, the builtin string encoding <code>string_escape</code>:</p>
<blockquote>
<p>Produce[s] a string that is suitable as string literal in Python source code</p>
</blockquote>
<p>...while the <code>unicode_escape</code>:</p>
<blockquote>
<p>Produce[s] a string that is suitable as Unicode literal in Python source code</p>
</blockquote>
<p>So, they should have roughly the same behaviour. BUT, they appear to treat single quotes differently:</p>
<pre class="lang-none prettyprint-override"><code>>>> print """before '" \0 after""".encode('string-escape')
before \'" \x00 after
>>> print """before '" \0 after""".encode('unicode-escape')
before '" \x00 after
</code></pre>
<p>The <code>string_escape</code> escapes the single quote while the Unicode one does not. Is it safe to assume that I can simply:</p>
<pre><code>>>> escaped = my_string.encode('unicode-escape').replace("'", "\\'")
</code></pre>
<p>...and get the expected behaviour?</p>
<p><strong>Edit:</strong> Just to be super clear, the expected behavior is getting something suitable as a literal.</p> | 3,001,998 | 2 | 0 | null | 2010-06-03 19:18:47.517 UTC | 19 | 2021-09-07 05:48:55.957 UTC | 2021-09-07 05:48:55.957 UTC | null | 10,669,875 | null | 66,502 | null | 1 | 29 | python|encoding|escaping|python-2.x|quotes | 121,558 | <p>According to my interpretation of the implementation of <code>unicode-escape</code> and the unicode <code>repr</code> in the CPython 2.6.5 source, yes; the only difference between <code>repr(unicode_string)</code> and <code>unicode_string.encode('unicode-escape')</code> is the inclusion of wrapping quotes and escaping whichever quote was used.</p>
<p>They are both driven by the same function, <code>unicodeescape_string</code>. This function takes a parameter whose sole function is to toggle the addition of the wrapping quotes and escaping of that quote.</p> |
40,992,111 | MongoDB join data inside an array of objects | <p>I have document like this in a collection called <strong>diagnoses</strong> :</p>
<pre><code> {
"_id" : ObjectId("582d43d18ec3f432f3260682"),
"patientid" : ObjectId("582aacff3894c3afd7ad4677"),
"doctorid" : ObjectId("582a80c93894c3afd7ad4675"),
"medicalcondition" : "high fever, cough, runny nose.",
"diagnosis" : "Viral Flu",
"addmissiondate" : "2016-01-12",
"dischargedate" : "2016-01-16",
"bhtno" : "125",
"prescription" : [
{
"drug" : ObjectId("58345e0e996d340bd8126149"),
"instructions" : "Take 2 daily, after meals."
},
{
"drug" : ObjectId("5836bc0b291918eb42966320"),
"instructions" : "Take 1 daily, after meals."
}
]
}
</code></pre>
<p>The <strong>drug</strong> id inside the prescription object array is from a separate collection called <strong>drugs</strong>, see sample document below :</p>
<pre><code>{
"_id" : ObjectId("58345e0e996d340bd8126149"),
"genericname" : "Paracetamol Tab 500mg",
"type" : "X",
"isbrand" : false
}
</code></pre>
<p>I am trying to create a mongodb query using the native node.js driver to get a result like this:</p>
<pre><code> {
"_id" : ObjectId("582d43d18ec3f432f3260682"),
"patientid" : ObjectId("582aacff3894c3afd7ad4677"),
"doctorid" : ObjectId("582a80c93894c3afd7ad4675"),
"medicalcondition" : "high fever, cough, runny nose.",
"diagnosis" : "Viral Flu",
"addmissiondate" : "2016-01-12",
"dischargedate" : "2016-01-16",
"bhtno" : "125",
"prescription" : [
{
"drug" :
{
"_id" : ObjectId("58345e0e996d340bd8126149"),
"genericname" : "Paracetamol Tab 500mg",
"type" : "X",
"isbrand" : false
},
"instructions" : "Take 2 daily, after meals."
},
...
]
}
</code></pre>
<p>Any advice on how to approach a similar result like this is much appreciated, thanks.</p> | 40,992,764 | 2 | 0 | null | 2016-12-06 09:39:16.173 UTC | 9 | 2021-01-05 13:02:11.187 UTC | 2017-09-22 18:01:22.247 UTC | null | -1 | null | 4,574,359 | null | 1 | 16 | mongodb|mongodb-query|aggregation-framework|nosql | 13,616 | <p><strong>Using MongoDB 3.4.4 and newer</strong></p>
<p>With the aggregation framework, the <strong><a href="https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/#pipe._S_lookup" rel="noreferrer"><code>$lookup</code></a></strong> operators supports arrays</p>
<pre><code>db.diagnoses.aggregate([
{ "$addFields": {
"prescription": { "$ifNull" : [ "$prescription", [ ] ] }
} },
{ "$lookup": {
"from": "drugs",
"localField": "prescription.drug",
"foreignField": "_id",
"as": "drugs"
} },
{ "$addFields": {
"prescription": {
"$map": {
"input": "$prescription",
"in": {
"$mergeObjects": [
"$$this",
{ "drug": {
"$arrayElemAt": [
"$drugs",
{
"$indexOfArray": [
"$drugs._id",
"$$this.drug"
]
}
]
} }
]
}
}
}
} },
{ "$project": { "drugs": 0 } }
])
</code></pre>
<p><strong>For older MongoDB versions:</strong></p>
<p>You can create a pipeline that first flattens the <code>prescription</code> array using the <strong><a href="https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/#pipe._S_unwind" rel="noreferrer"><code>$unwind</code></a></strong> operator and a <strong><a href="https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/#pipe._S_lookup" rel="noreferrer"><code>$lookup</code></a></strong> subsequent pipeline step to do a "left outer join" on the "drugs" collection. Apply another <strong><a href="https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/#pipe._S_unwind" rel="noreferrer"><code>$unwind</code></a></strong> operation on the created array from the "joined" field. <strong><a href="https://docs.mongodb.com/manual/reference/operator/aggregation/group/#pipe._S_group" rel="noreferrer"><code>$group</code></a></strong> the previously flattened documents from the first pipeline where there <strong><a href="https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/#pipe._S_unwind" rel="noreferrer"><code>$unwind</code></a></strong> operator outputs a document for each element in the prescription array.</p>
<p>Assembling the above pipeline, run the following aggregate operation:</p>
<pre><code>db.diagnoses.aggregate([
{
"$project": {
"patientid": 1,
"doctorid": 1,
"medicalcondition": 1,
"diagnosis": 1,
"addmissiondate": 1,
"dischargedate": 1,
"bhtno": 1,
"prescription": { "$ifNull" : [ "$prescription", [ ] ] }
}
},
{
"$unwind": {
"path": "$prescription",
"preserveNullAndEmptyArrays": true
}
},
{
"$lookup": {
"from": "drugs",
"localField": "prescription.drug",
"foreignField": "_id",
"as": "prescription.drug"
}
},
{ "$unwind": "$prescription.drug" },
{
"$group": {
"_id": "$_id",
"patientid" : { "$first": "$patientid" },
"doctorid" : { "$first": "$doctorid" },
"medicalcondition" : { "$first": "$medicalcondition" },
"diagnosis" : { "$first": "$diagnosis" },
"addmissiondate" : { "$first": "$addmissiondate" },
"dischargedate" : { "$first": "$dischargedate" },
"bhtno" : { "$first": "$bhtno" },
"prescription" : { "$push": "$prescription" }
}
}
])
</code></pre>
<p><strong>Sample Output</strong></p>
<pre><code>{
"_id" : ObjectId("582d43d18ec3f432f3260682"),
"patientid" : ObjectId("582aacff3894c3afd7ad4677"),
"doctorid" : ObjectId("582a80c93894c3afd7ad4675"),
"medicalcondition" : "high fever, cough, runny nose.",
"diagnosis" : "Viral Flu",
"addmissiondate" : "2016-01-12",
"dischargedate" : "2016-01-16",
"bhtno" : "125",
"prescription" : [
{
"drug" : {
"_id" : ObjectId("58345e0e996d340bd8126149"),
"genericname" : "Paracetamol Tab 500mg",
"type" : "X",
"isbrand" : false
},
"instructions" : "Take 2 daily, after meals."
},
{
"drug" : {
"_id" : ObjectId("5836bc0b291918eb42966320"),
"genericname" : "Paracetamol Tab 100mg",
"type" : "Y",
"isbrand" : false
},
"instructions" : "Take 1 daily, after meals."
}
]
}
</code></pre> |
32,683,129 | Android DataBinding error. Could not find accessor | <p>I'm getting the following error when I try to run my app:</p>
<pre><code>Error:Execution failed for task ':app:compileDevelopmentDebugJavaWithJavac'.
> java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:Could not find accessor java.lang.String.giftRecipientName redacted.xml loc:182:63 - 182:93 ****\ data binding error ****
</code></pre>
<p>I have an Order object which looks like this:</p>
<pre><code>public class Order {
public Address address;
// unrelated fields and methods
}
</code></pre>
<p>The nested Address object looks like this:</p>
<pre><code>public class Address {
public String addressLine1;
public String addressLine2;
public String giftRecipientName;
public Boolean isGift;
}
</code></pre>
<p>In my .xml I am doing the following:</p>
<pre><code><layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="order" type="example.redacted.models.Order"/>
</data>
// widgets and whatnot
<TextView
android:id="@+id/gift_recipientTV"
android:layout_column="1"
android:layout_weight="1"
android:layout_width="0dp"
android:textStyle="bold"
android:gravity="right"
android:text='@{order.address.isGift ? order.address.giftRecipientName : "" }'/>
</code></pre>
<p>Lastly in my fragment:</p>
<pre><code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RedactedBinding dataBinding = DataBindingUtil.inflate(inflater, R.layout.redacted, container, false);
dataBinding.setOrder(_order);
return dataBinding.getRoot();
}
</code></pre> | 32,683,130 | 10 | 0 | null | 2015-09-20 19:04:46.593 UTC | 2 | 2021-10-04 09:32:41.457 UTC | null | null | null | null | 2,590,478 | null | 1 | 31 | android|data-binding|android-databinding | 32,538 | <p>After hours of trial and error it seems that Android data-binding looks for getters <em>before</em> it looks at public fields. My Order object had a helper method called getAddress </p>
<pre><code>public class Order {
public Address address;
public String getAddress() {
return address.addressLine1 + address.addressLine2;
}
}
</code></pre>
<p>The binder was calling that method instead of accessing the public Address field. I put the getAddress method inside the Address object (where it probably should have been to begin with) and the app compiled.</p> |
42,338,352 | How to add configuration values in AppSettings.json in Azure functions. Is there any structure for it? | <p>What is the standard structure to add keys to <code>appsettings.json</code>?
Also, how to read those values in our <code>run.csx</code>?
Normally in app.config, we had <code>ConfigurationManager.GetSettings["SettingName"];</code>
Is there any similar implementation in Azure Function?</p> | 45,984,082 | 7 | 0 | null | 2017-02-20 07:03:24.047 UTC | 3 | 2019-05-20 08:03:54.107 UTC | 2017-02-26 21:44:00.29 UTC | null | 707,458 | null | 2,472,243 | null | 1 | 20 | azure|azure-functions|appsettings | 45,160 | <p>As stated <a href="https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local#local-settings-file" rel="noreferrer">here</a></p>
<blockquote>
<p>These settings can also be read in your code as environment variables. In C#, use <code>System.Environment.GetEnvironmentVariable</code> or <code>ConfigurationManager.AppSettings</code>. In JavaScript, use <code>process.env</code>. Settings specified as a system environment variable take precedence over values in the <code>local.settings.json</code> file.</p>
</blockquote> |
33,422,627 | laravel 5.1 - Dynamically create Class object based on string | <p>i want to create object of class base on string which come from URL parameter.</p>
<p>for example :</p>
<pre><code> http://localhost/CSWeb/api/search/Slideshare
</code></pre>
<p>in above URL <code>Slideshare</code> is parameter which get in <code>apiController->indexAction</code>.</p>
<p><code>slideshare.php class</code></p>
<pre><code><?php
namespace App\Http\API;
class slideshare
{
public function index()
{
return 'any data';
}
}
</code></pre>
<p><code>apiController.php</code></p>
<pre><code>namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Auth;
use App\Http\API\Slideshare;
class apiController extends Controller
{
public function index($source)
{
$controller= new $source;
return $controller->index();
// if i change code to $controller= new Slideshare; it works fine
}
}
</code></pre>
<p>laravel error when i use parameter string to create class object </p>
<blockquote>
<p>FatalErrorException in apiController.php line 17: Class
'Slideshare' not found</p>
</blockquote>
<p>if i change code to </p>
<pre><code>$controller= new Slideshare; it works fine
</code></pre>
<p>Thank you in advance</p> | 33,422,826 | 1 | 0 | null | 2015-10-29 19:06:58.143 UTC | 7 | 2015-10-29 19:47:36.713 UTC | 2015-10-29 19:12:00.547 UTC | null | 4,302,471 | null | 4,302,471 | null | 1 | 12 | php|laravel-5.1 | 39,429 | <p>When creating PHP objects with strings, you must provide the full qualified name of the class (a.k.a include the namespace). So, you should have something like this:</p>
<pre><code>$className = 'App\\Http\\API\\' . $source;
$controller = new $className;
return $controller->index();
</code></pre>
<p>Another way to do it, if you are sure that the class you want to instantiate lives in the same namespace as your code, you can use:</p>
<pre><code>$className = __NAMESPACE__ . '\\' . $source;
$controller = new $className;
return $controller->index();
</code></pre>
<p>A more elaborated way of achieving the same results is through the Factory Design Pattern. Basically you create a class that is responsible for instantiating elements, and you delegate the task of actually creating those objects to that class. Something along those lines:</p>
<pre><code>class Factory {
function __construct ( $namespace = '' ) {
$this->namespace = $namespace;
}
public function make ( $source ) {
$name = $this->namespace . '\\' . $source;
if ( class_exists( $name ) ) {
return new $name();
}
}
}
$factory = new Factory( __NAMESPACE__ );
$controller = $factory->make( $source );
</code></pre>
<p>The advantage of this approach is that the responsability of creating the objects now lies in the Factory, and if you ever need to change it, maybe allow for aliases, add some additional security measures, or any other thing, you just need to change that code in one place, but as long as the class signature remains, your code keeps working.</p>
<p>An interesting tutorial on factories:
<a href="http://culttt.com/2014/03/19/factory-method-design-pattern/">http://culttt.com/2014/03/19/factory-method-design-pattern/</a></p>
<p>Source:
<a href="http://nl3.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.new">http://nl3.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.new</a>
<a href="http://php.net/manual/en/language.namespaces.nsconstants.php">http://php.net/manual/en/language.namespaces.nsconstants.php</a></p> |
2,220,575 | How to implement an audio player for Android using MediaPlayer And MediaController? | <p>I want to create an Android application that is a client for an Internet radio station. And I want it look native to Android? But im confused with Android API logic and documentation. What i've got is that I need MediaPlayer and MediaController classes. Am I right, and is there any good example of AUDIO player for Android?</p>
<p>Especially, I'm very interested how to use <code>MediaPlayer</code> and <code>MediaController</code> classes together.</p>
<p>UPD:</p>
<p>Finally I've got the code, that does exactly what I want:</p>
<pre><code>Intent i = new Intent(Intent.ACTION_VIEW);
Uri u = Uri.parse(%file_uri%));
i.setData(u);
startActivity(i);
</code></pre> | 2,220,605 | 1 | 0 | null | 2010-02-08 09:31:56.71 UTC | 14 | 2018-08-29 12:06:09.29 UTC | 2011-06-30 07:07:37.993 UTC | null | 674,530 | null | 268,532 | null | 1 | 7 | java|android|audio|media-player | 45,603 | <p>you can look at those links :</p>
<p><a href="http://www.helloandroid.com/tutorials/musicdroid-audio-player-part-i" rel="nofollow noreferrer">http://www.helloandroid.com/tutorials/musicdroid-audio-player-part-i</a></p>
<p>Hope it will help.</p>
<p>[EDIT]</p>
<p>You have also some example on the official android developer website :</p>
<p><a href="http://developer.android.com/guide/topics/media/index.html" rel="nofollow noreferrer">http://developer.android.com/guide/topics/media/index.html</a></p> |
1,830,050 | Why same origin policy for XMLHttpRequest | <p>Why do browsers apply the same origin policy to XMLHttpRequest? It's really inconvenient for developers, but it appears it does little in actually stopping hackers.
There are workarounds, they can still include javascript from outside sources (the power behind JSONP).</p>
<p>It seems like an outdated "feature" in a web that's largely interlinked.</p> | 1,830,176 | 1 | 3 | 2009-12-02 01:05:52.807 UTC | 2009-12-02 01:05:52.807 UTC | 11 | 2020-02-11 18:14:57.1 UTC | 2011-10-30 13:42:40.04 UTC | null | 85,821 | null | 85,821 | null | 1 | 30 | security|jsonp|javascript-security | 4,734 | <p>Because an XMLHttpRequest passes the user's authentication tokens. If the user were logged onto example.com with basic auth or some cookies, then visited attacker.com, the latter site could create an XMLHttpRequest to example.com with full authorisation for that user and read any private page that the user could (then forward it back to the attacker).</p>
<p>Because putting secret tokens in webapp pages is the way to stop simple Cross-Site-Request-Forgery attacks, this means attacker.com could take any on-page actions the user could at example.com without any consent or interaction from them. Global XMLHttpRequest is global cross-site-scripting.</p>
<p>(Even if you had a version of XMLHttpRequest that didn't pass authentication, there are still problems. For example an attacker could make requests out to other non-public machines on your intranet and read any files it can download from them which may not be meant for public consumption. <code><script></code> tags already suffer from a limited form of this kind of vulnerability, but the fully-readable responses of XMLHttpRequest would leak all kinds of files instead of a few unfortunately-crafted ones that can parse as JavaScript.)</p> |
19,960,831 | Rspec: expect vs expect with block - what's the difference? | <p>Just learning rspec syntax and I noticed that this code works:</p>
<pre><code> context "given a bad list of players" do
let(:bad_players) { {} }
it "fails to create given a bad player list" do
expect{ Team.new("Random", bad_players) }.to raise_error
end
end
</code></pre>
<p>But this code doesn't:</p>
<pre><code> context "given a bad list of players" do
let(:bad_players) { {} }
it "fails to create given a bad player list" do
expect( Team.new("Random", bad_players) ).to raise_error
end
end
</code></pre>
<p>It gives me this error:</p>
<pre><code>Team given a bad list of players fails to create given a bad player list
Failure/Error: expect( Team.new("Random", bad_players) ).to raise_error
Exception:
Exception
# ./lib/team.rb:6:in `initialize'
# ./spec/team_spec.rb:23:in `new'
# ./spec/team_spec.rb:23:in `block (3 levels) in <top (required)>'
</code></pre>
<p>My question is:</p>
<ol>
<li>Why does this happen?</li>
<li>What is the difference between the former and later example exactly in ruby?</li>
</ol>
<p>I am also looking for <strong>rules</strong> on when to use one over the other</p>
<p>One more example of the same but inverse results, where this code works:</p>
<pre><code> it "has a list of players" do
expect(Team.new("Random").players).to be_kind_of Array
end
</code></pre>
<p>But this code fails</p>
<pre><code> it "has a list of players" do
expect{ Team.new("Random").players }.to be_kind_of Array
end
</code></pre>
<p>Error I get in this case is:</p>
<pre><code>Failure/Error: expect{ Team.new("Random").players }.to be_kind_of Array
expected #<Proc:0x007fbbbab29580@/Users/amiterandole/Documents/current/ruby_sandbox/tdd-ruby/spec/team_spec.rb:9> to be a kind of Array
# ./spec/team_spec.rb:9:in `block (2 levels) in <top (required)>'
</code></pre>
<p>The class I am testing looks like this:</p>
<pre><code>class Team
attr_reader :name, :players
def initialize(name, players = [])
raise Exception unless players.is_a? Array
@name = name
@players = players
end
end
</code></pre> | 19,962,317 | 2 | 0 | null | 2013-11-13 17:48:56.15 UTC | 10 | 2013-11-13 19:09:36.67 UTC | 2013-11-13 18:16:18.66 UTC | null | 228,521 | null | 228,521 | null | 1 | 41 | ruby|tdd|rspec2 | 30,541 | <p>As has been mentioned:</p>
<pre><code>expect(4).to eq(4)
</code></pre>
<p>This is specifically testing the value that you've sent in as the parameter to the method. When you're trying to test for raised errors when you do the same thing:</p>
<pre><code>expect(raise "fail!").to raise_error
</code></pre>
<p>Your argument is evaluated <em>immediately</em> and that exception will be thrown and your test will blow up right there.</p>
<p>However, when you use a block (and this is basic ruby), the block contents isn't executed immediately - it's execution is determined by the method you're calling (in this case, the <code>expect</code> method handles when to execute your block):</p>
<pre><code>expect{raise "fail!"}.to raise_error
</code></pre>
<p>We can look at an example method that might handle this behavior:</p>
<pre><code>def expect(val=nil)
if block_given?
begin
yield
rescue
puts "Your block raised an error!"
end
else
puts "The value under test is #{val}"
end
end
</code></pre>
<p>You can see here that it's the <code>expect</code> method that is manually rescuing your error so that it can test whether or not errors are raised, etc. <code>yield</code> is a ruby method's way of executing whatever block was passed to the method.</p> |
21,495,273 | Convert HTML to PDF in ASP.NET MVC | <p>Im working in a project which requires current html page to convert in pdf and that pdf will automatically save on button click on server and its reference will be save in database.I can convert the view if its data comes from data base but the data in this form is static that means on the view it has so many radio button and text box in which i can write the detail and check the check box on after clicking save button it will save on the server and and its reference will save in the data base.</p>
<p>the reason is that im not saving the data in database is that the report is less use full for the client but if i save the data in data base then the database become very huge and its become complicate to handle. because the report has approx 100 fields.
so please if any one can help me in it.</p> | 59,891,526 | 9 | 0 | null | 2014-02-01 07:11:52.337 UTC | 5 | 2021-04-21 06:59:38.647 UTC | 2014-02-06 07:08:55.637 UTC | null | 727,208 | null | 3,244,360 | null | 1 | 10 | asp.net-mvc|pdf-conversion | 57,163 | <p>I have used Canvas to PDF and that worked great for me. Here is the perfect tutorial for the same: <a href="https://www.freakyjolly.com/jspdf-multipage-example-generate-multipage-pdf-using-single-canvas-of-html-document-using-jspdf/" rel="nofollow noreferrer">https://www.freakyjolly.com/jspdf-multipage-example-generate-multipage-pdf-using-single-canvas-of-html-document-using-jspdf/</a></p>
<p>Thank you everyone.</p> |
35,096,746 | Substituting parameters in log message and add a Throwable in Log4j 2 | <p>I am trying to log an exception, and would like to include another variable's value in the log message. Is there a Logger API that does this? </p>
<pre><code>logger.error("Logging in user {} with birthday {}", user.getName(), user.getBirthdayCalendar(), exception);
</code></pre> | 35,097,048 | 2 | 0 | null | 2016-01-30 00:59:51.22 UTC | 8 | 2021-09-30 22:33:43.617 UTC | null | null | null | null | 115,622 | null | 1 | 41 | java|exception|logging|log4j | 28,657 | <p>Have you tried looking at <a href="https://logging.apache.org/log4j/log4j-2.1/log4j-api/apidocs/org/apache/logging/log4j/message/ParameterizedMessage.html" rel="noreferrer">ParameterizedMessage</a>?</p>
<p>From the docs</p>
<blockquote>
<p>Parameters:</p>
<p>messagePattern - The message "format" string. This will be
a String containing "{}" placeholders where parameters should be
substituted.</p>
<p>objectArgs - The arguments for substitution.</p>
<p>throwable - A Throwable</p>
</blockquote>
<p>e.g.</p>
<pre><code>logger.error(new ParameterizedMessage("Logging in user {} with birthday {}", user.getName(), user.getBirthdayCalendar()), exception);
</code></pre> |
53,654,190 | What is the difference between registering and creating in Gradle Kotlin DSL | <p>There are two methods of creating, i.e. tasks, in Gradle (5.0+):</p>
<pre><code>tasks {
val javadocJar by creating(Jar::class) {
val javadoc by tasks
from(javadoc)
classifier = "javadoc"
}
}
</code></pre>
<p>and</p>
<pre><code>tasks {
val javadocJar by registering(Jar::class) {
val javadoc by tasks
from(javadoc)
classifier = "javadoc"
}
}
</code></pre>
<p>Basically the same API, so what's the difference?</p> | 53,654,412 | 2 | 0 | null | 2018-12-06 15:01:01.52 UTC | 7 | 2018-12-06 15:30:42.343 UTC | 2018-12-06 15:30:42.343 UTC | null | 750,510 | null | 750,510 | null | 1 | 31 | gradle|kotlin|gradle-kotlin-dsl | 12,236 | <p>See <a href="https://docs.gradle.org/current/userguide/kotlin_dsl.html#using_the_container_api" rel="noreferrer">https://docs.gradle.org/current/userguide/kotlin_dsl.html#using_the_container_api</a>:</p>
<pre><code>tasks.named("check")
tasks.register("myTask1")
</code></pre>
<blockquote>
<p>The above sample relies on the configuration avoidance APIs. If you need or want to eagerly configure or register container elements, simply replace named() with getByName() and register() with create().</p>
</blockquote>
<p>Difference between <code>creating</code> and <code>registering</code> (or <code>create</code> and <code>register</code> in Gradle versions prior to 5.0) is related to <code>Task Configuration Avoidance</code> new API, which is exaplined in details <a href="https://docs.gradle.org/current/userguide/task_configuration_avoidance.html" rel="noreferrer">here</a> (see <a href="https://docs.gradle.org/current/userguide/task_configuration_avoidance.html#sec:how_do_i_defer_creation" rel="noreferrer">this section</a>):</p>
<blockquote>
<p><em>How do I defer task creation?</em></p>
<p>This feature requires build authors to opt-in by migrating task creation from the TaskContainer.create(java.lang.String) APIs to the TaskContainer.register(java.lang.String) APIs. The register(…) API registers a task to be created at a later time if and only if the task is needed. The create(…) API continues to eagerly create and configure tasks when it is called.</p>
</blockquote> |
59,422,883 | Spring Boot : Custom Validation in Request Params | <p>I want to validate one of the request parameters in my controller . The request parameter should be from one of the list of given values , if not , an error should be thrown . In the below code , I want the request param orderBy to be from the list of values present in @ValuesAllowed.</p>
<pre class="lang-java prettyprint-override"><code>@RestController
@RequestMapping("/api/opportunity")
@Api(value = "Opportunity APIs")
@ValuesAllowed(propName = "orderBy", values = { "OpportunityCount", "OpportunityPublishedCount", "ApplicationCount",
"ApplicationsApprovedCount" })
public class OpportunityController {
@GetMapping("/vendors/list")
@ApiOperation(value = "Get all vendors")
public ResultWrapperDTO getVendorpage(@RequestParam(required = false) String term,
@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer size,
@RequestParam(required = false) String orderBy, @RequestParam(required = false) String sortDir) {
</code></pre>
<p>I have written a custom bean validator but somehow this is not working . Even if am passing any random values for the query param , its not validating and throwing an error.</p>
<pre class="lang-java prettyprint-override"><code>@Repeatable(ValuesAllowedMultiple.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {ValuesAllowedValidator.class})
public @interface ValuesAllowed {
String message() default "Field value should be from list of ";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String propName();
String[] values();
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>public class ValuesAllowedValidator implements ConstraintValidator<ValuesAllowed, Object> {
private String propName;
private String message;
private String[] values;
@Override
public void initialize(ValuesAllowed requiredIfChecked) {
propName = requiredIfChecked.propName();
message = requiredIfChecked.message();
values = requiredIfChecked.values();
}
@Override
public boolean isValid(Object object, ConstraintValidatorContext context) {
Boolean valid = true;
try {
Object checkedValue = BeanUtils.getProperty(object, propName);
if (checkedValue != null) {
valid = Arrays.asList(values).contains(checkedValue.toString().toLowerCase());
}
if (!valid) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(message.concat(Arrays.toString(values)))
.addPropertyNode(propName).addConstraintViolation();
}
} catch (IllegalAccessException e) {
log.error("Accessor method is not available for class : {}, exception : {}", object.getClass().getName(), e);
return false;
} catch (NoSuchMethodException e) {
log.error("Field or method is not present on class : {}, exception : {}", object.getClass().getName(), e);
return false;
} catch (InvocationTargetException e) {
log.error("An exception occurred while accessing class : {}, exception : {}", object.getClass().getName(), e);
return false;
}
return valid;
}
}
</code></pre> | 59,465,567 | 3 | 0 | null | 2019-12-20 09:34:37.59 UTC | 11 | 2022-06-14 21:55:31.577 UTC | 2019-12-24 08:56:11.357 UTC | null | 11,733,759 | null | 9,311,364 | null | 1 | 15 | spring-boot|validation|controller|spring-annotations|http-request-parameters | 50,154 | <p>Case 1: If the annotation ValuesAllowed is not triggered at all, it could be because of not annotating the controller with @Validated.</p>
<pre class="lang-java prettyprint-override"><code>@Validated
@ValuesAllowed(propName = "orderBy", values = { "OpportunityCount", "OpportunityPublishedCount", "ApplicationCount", "ApplicationsApprovedCount" })
public class OpportunityController {
@GetMapping("/vendors/list")
public String getVendorpage(@RequestParam(required = false) String term,..{
}
</code></pre>
<p>Case 2: If it is triggered and throwing an error, it could be because of the <code>BeanUtils.getProperty</code> not resolving the properties and throwing exceptions.</p>
<p>If the above solutions do not work, you can try moving the annotation to the method level and update the Validator to use the list of valid values for the <code>OrderBy</code> parameter. This worked for me. Below is the sample code.</p>
<pre class="lang-java prettyprint-override"><code>@RestController
@RequestMapping("/api/opportunity")
@Validated
public class OpportunityController {
@GetMapping("/vendors/list")
public String getVendorpage(@RequestParam(required = false) String term,
@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer size,
@ValuesAllowed(propName = "orderBy", values = { "OpportunityCount", "OpportunityPublishedCount", "ApplicationCount",
"ApplicationsApprovedCount" }) @RequestParam(required = false) String orderBy, @RequestParam(required = false) String sortDir) {
return "success";
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { ValuesAllowed.Validator.class })
public @interface ValuesAllowed {
String message() default "Field value should be from list of ";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String propName();
String[] values();
class Validator implements ConstraintValidator<ValuesAllowed, String> {
private String propName;
private String message;
private List<String> allowable;
@Override
public void initialize(ValuesAllowed requiredIfChecked) {
this.propName = requiredIfChecked.propName();
this.message = requiredIfChecked.message();
this.allowable = Arrays.asList(requiredIfChecked.values());
}
public boolean isValid(String value, ConstraintValidatorContext context) {
Boolean valid = value == null || this.allowable.contains(value);
if (!valid) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(message.concat(this.allowable.toString()))
.addPropertyNode(this.propName).addConstraintViolation();
}
return valid;
}
}
}
</code></pre> |
34,580,033 | Spring io @Autowired: The blank final field may not have been initialized | <p>what I assume is a pretty basic question here-</p>
<p>There are several flavors of questions regarding this error, but none in the first 5 results that have the added nuance of Spring.</p>
<p>I have the beginnings of a REST-ful webapp written in spring. I am trying to connect it to a database.</p>
<p>I have an entity named Workspace and am trying to use the spring injection of a bean( correct terminology ?) to save an instance of the workspace entity</p>
<pre><code>package com.parrit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.parrit.models.Workspace;
import com.parrit.models.WorkspaceRepository;
@RestController
@RequestMapping("/workspace")
public class WorkspaceController {
@Autowired
private final WorkspaceRepository repository;
@RequestMapping(method = RequestMethod.POST)
void save( @RequestBody String workspaceHTML) {
Workspace ws = new Workspace();
ws.setHTML(workspaceHTML);
repository.save(ws);
}
}
</code></pre>
<p>My error is on the repository variable <code>private final WorkspaceRepository repository</code>. The compiler is complaining that it may not be initialized and attempting to run the app yields the same result.</p>
<p>How do I get an instance of this repository object into my controller in order to do save operations on it?</p> | 34,580,087 | 2 | 0 | null | 2016-01-03 18:28:43.707 UTC | 8 | 2016-01-03 18:52:11.237 UTC | 2016-01-03 18:52:11.237 UTC | null | 380,338 | null | 1,529,524 | null | 1 | 31 | java|spring|spring-mvc|spring-data | 33,927 | <p>Having <code>@Autowired</code> and final on a field are contradictory.</p>
<p>The latter says: this variable has one and only one value, and it's initialized at construction time.</p>
<p>The former says: Spring will construct the object, leaving this field as null (its default value). Then Spring will use reflection to initialize this field with a bean of type WorkspaceRepository.</p>
<p>If you want final fields autowired, use constructor injection, just like you would do if you did the injection by yourself:</p>
<pre><code>@Autowired
public WorkspaceController(WorkspaceRepository repository) {
this.repository = repository;
}
</code></pre> |
47,893,328 | Checking if a particular value exists in the Firebase database | <p>I am making an Android application using <code>Firebase</code> realtime database. When a new user registers on my app, that user's data is saved in the Firebase database. </p>
<p>A user has to provide the following details to register:</p>
<ol>
<li>Full Name</li>
<li>Email </li>
<li>Username</li>
<li>Password</li>
</ol>
<h3>Database Structure</h3>
<p><a href="https://i.stack.imgur.com/KPTaX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KPTaX.png" alt="enter image description here"></a></p>
<p>Whenever a new user tries to register, I have to make sure that each user's username is unique so I check the database if the <code>username</code> entered by the user already exists in the database or not.</p>
<p>To do this, I wrote the following method:</p>
<pre><code>private boolean usernameExists(String username) {
DatabaseReference fdbRefer = FirebaseDatabase.getInstance().getReference("Users/"+username);
return (fdbRefer != null);
}
</code></pre>
<p>My logic behind this method is that if <code>getReference</code> method cannot find reference to the specified path, it will return null so that I can return whether <code>fdbRefer</code> is <code>null</code> or not. If <code>fdbRefer</code> is <code>null</code>, then it means that <code>username</code> doesn't exist in the database.</p>
<h3>Problem</h3>
<p>Problem with this method is that it always returns <code>true</code> whether the entered <code>username</code> exists in the database or not. Which led me to believe that <code>fdbRefer</code> is never <code>null</code>. </p>
<p>This brings me to my question... </p>
<h3>Question</h3>
<p>What does <code>getReference</code> method return when it can't find the specified path in the <code>firebase</code> database and what's the correct way to check if the <code>username</code> already exists in the database or not?</p> | 47,893,879 | 6 | 0 | null | 2017-12-19 18:44:35.873 UTC | 5 | 2022-03-19 12:44:01.52 UTC | 2019-01-31 08:07:44.413 UTC | null | 5,246,885 | user7500403 | null | null | 1 | 14 | java|android|firebase|firebase-realtime-database | 40,873 | <p>To check the existence of a user, please use the below code:</p>
<pre><code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userNameRef = rootRef.child("Users").child("Nick123");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.exists()) {
//create new user
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
userNameRef.addListenerForSingleValueEvent(eventListener);
</code></pre>
<p>You can also use a Query to achieve the same thing like this:</p>
<pre><code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Users").orderByChild("userName").equalTo("Nick123");
query.addValueEventListener(/* ... */);
</code></pre>
<p>This is another approach which is looping through the entire <code>Users</code> node but is not just using a direct reference to a single user. This option is more likely to be used when you are using as a unique identifier beteeen users the <code>uid</code> instead of the user name (as you do right now). So if your database structure might looks similar to this:</p>
<pre><code>Firebase-root
|
--- Users
|
--- uid
|
--- userName: "Test User"
|
--- emailAddress: "[email protected]"
</code></pre>
<p>The second solution is the recommended one.</p>
<p>There is also another solution which involves you to create another node named <code>userNames</code>, in which you can hold only the unique user names. Please also find below the corresponding security rules:</p>
<pre><code>"Users": {
"$uid": {
".write": "auth !== null && auth.uid === $uid",
".read": "auth !== null && auth.provider === 'password'",
"userName": {
".validate": "
!root.child('userNames').child(newData.val()).exists() ||
root.child('userNames').child(newData.val()).val() == $uid"
}
}
}
</code></pre>
<p>But since in this case, your user name is already the name of the node, I recommend you go ahead with the first one.</p> |
40,526,496 | Vertical scrollbar for frame in Tkinter, Python | <p>My aim is to have a scrollbar that stays at the right-side of a full-screen window, allowing the user to scroll up and down through various different widgets (such as labels & buttons).
From other answers I've seen on this site, I've come to the conclusion that a scrollbar has to be assigned to a canvas in order for it to function properly, which I have tried to include in my code but have not had much success with.</p>
<p>The below code shows a simplified version of what I've managed to accomplish so far:</p>
<pre><code>from tkinter import *
root = Tk()
root.state("zoomed")
root.title("Vertical Scrollbar")
frame = Frame(root)
canvas = Canvas(frame)
Label(canvas, text = "Test text 1\nTest text 2\nTest text 3\nTest text 4\nTest text 5\nTest text 6\nTest text 7\nTest text 8\nTest text 9", font = "-size 100").pack()
scrollbar = Scrollbar(frame)
scrollbar.pack(side = RIGHT, fill = Y)
canvas.configure(yscrollcommand = scrollbar.set)
canvas.pack()
frame.pack()
root.mainloop()
</code></pre>
<p>I'm facing two issues when running this code:</p>
<p>One is that the scrollbar is inactive, and doesn't allow for the user to scroll down to view the rest of the text.</p>
<p>The other is that the scrollbar is attached to the right-side of the text, rather than the right-side of the window.</p>
<p>So far, none of the other answers I've found on this site have enabled me to amend my code to support a fully-functioning scrollbar for my program. I'd be very grateful for any help anyone reading this could provide.</p> | 40,539,365 | 2 | 5 | null | 2016-11-10 11:27:17.283 UTC | 2 | 2020-12-20 18:58:48.287 UTC | null | null | null | null | 2,946,537 | null | 1 | 8 | python|python-3.x|tkinter|scrollbar|tkinter-canvas | 45,824 | <p>See again link: <a href="https://stackoverflow.com/a/3092341/7432">https://stackoverflow.com/a/3092341/7432</a></p>
<p>It shows how to create scrolled frame - and then you can add all widgets in this frame.</p>
<pre><code>import tkinter as tk
def on_configure(event):
# update scrollregion after starting 'mainloop'
# when all widgets are in canvas
canvas.configure(scrollregion=canvas.bbox('all'))
root = tk.Tk()
# --- create canvas with scrollbar ---
canvas = tk.Canvas(root)
canvas.pack(side=tk.LEFT)
scrollbar = tk.Scrollbar(root, command=canvas.yview)
scrollbar.pack(side=tk.LEFT, fill='y')
canvas.configure(yscrollcommand = scrollbar.set)
# update scrollregion after starting 'mainloop'
# when all widgets are in canvas
canvas.bind('<Configure>', on_configure)
# --- put frame in canvas ---
frame = tk.Frame(canvas)
canvas.create_window((0,0), window=frame, anchor='nw')
# --- add widgets in frame ---
l = tk.Label(frame, text="Hello", font="-size 50")
l.pack()
l = tk.Label(frame, text="World", font="-size 50")
l.pack()
l = tk.Label(frame, text="Test text 1\nTest text 2\nTest text 3\nTest text 4\nTest text 5\nTest text 6\nTest text 7\nTest text 8\nTest text 9", font="-size 20")
l.pack()
# --- start program ---
root.mainloop()
</code></pre> |
32,334,167 | Is it possible to start multiple docker daemons on the same machine | <p>And if it is possible, how would you configure each daemon - graph location, images location, etc?</p> | 34,058,675 | 3 | 0 | null | 2015-09-01 14:24:44.013 UTC | 16 | 2019-03-23 20:24:50.823 UTC | null | null | null | null | 244,754 | null | 1 | 34 | docker | 15,240 | <p>Yes, it's perfectly possible to run two Docker daemons on a single host even without Docker Machine. As of Docker 18.09.0-ce, the following <code>dockerd</code> flags are the ones that could cause conflicts if two daemons used the defaults:</p>
<pre><code> -b, --bridge string Attach containers to a network bridge
--exec-root string Root directory for execution state files (default "/var/run/docker")
--data-root string Root directory of persistent Docker state (default "/var/lib/docker")
-H, --host list Daemon socket(s) to connect to
-p, --pidfile string Path to use for daemon PID file (default "/var/run/docker.pid")
</code></pre>
<ul>
<li><p>The default for <code>--bridge</code> is <code>docker0</code>, and if you're not using the default, you must create and configure the bridge manually (Docker won't create/manage it for you). More details below.</p></li>
<li><p><code>--exec-root</code> is where container state is stored (default: <code>/var/run/docker</code>).</p></li>
<li><p><code>--data-root</code> is where images are stored (default: <code>/var/lib/docker</code>).</p></li>
<li><p><code>--host</code> specifies where the Docker daemon will listen for client connections. If unspecified, it defaults to <code>/var/run/docker.sock</code>.</p></li>
<li><p><code>--pidfile</code> is where the process ID of the daemon is stored (default: <code>/var/run/docker.pid</code>).</p></li>
</ul>
<p>So, as long as your two daemons use different values for these flags, you can run them on the same host. Example script (including network setup):</p>
<pre class="lang-sh prettyprint-override"><code>#!/bin/sh
## name: altdocker.sh
set -e -x
: ${bridge=altdocker}
: ${base=$HOME/$bridge}
# Set up bridge network:
if ! ip link show $bridge > /dev/null 2>&1
then
sudo ip link add name $bridge type bridge
sudo ip addr add ${net:-"10.20.30.1/24"} dev $bridge
sudo ip link set dev $bridge up
fi
sudo dockerd \
--bridge=$bridge \
--data-root=$base.data \
--exec-root=$base.exec \
--host=unix://$base.socket \
--pidfile=$base.pid
</code></pre>
<p>Example usage:</p>
<pre class="lang-sh prettyprint-override"><code>## in one terminal
$ env net=10.9.8.7/24 /bin/sh altdocker.sh
# ... log output ...
## in another terminal
$ docker -H unix://$HOME/altdocker.socket run --rm -i -t alpine sh
/ # echo hereiam
hereiam
</code></pre>
<hr>
<p>Updated for changes from Docker 1.9.1 to 18.09.0-ce, in case anyone is using a very old version:</p>
<pre><code>┌───────────────┬─────────────┐
│ 1.9.1 │ 18.09.0-ce │
├───────────────┼─────────────┤
│ docker daemon │ dockerd │
│ -g / --graph │ --exec-root │
└───────────────┴─────────────┘
</code></pre> |
56,505,043 | How to make view the size of another view in SwiftUI | <p>I'm trying to recreate a portion of the Twitter iOS app to learn SwiftUI and am wondering how to dynamically change the width of one view to be the width of another view. In my case, to have the underline be the same width as the Text view. </p>
<p>I have attached a screenshot to try and better explain what I'm referring to. Any help would be greatly appreciated, thanks!</p>
<p>Also here is the code I have so far:</p>
<pre><code>import SwiftUI
struct GridViewHeader : View {
@State var leftPadding: Length = 0.0
@State var underLineWidth: Length = 100
var body: some View {
return VStack {
HStack {
Text("Tweets")
.tapAction {
self.leftPadding = 0
}
Spacer()
Text("Tweets & Replies")
.tapAction {
self.leftPadding = 100
}
Spacer()
Text("Media")
.tapAction {
self.leftPadding = 200
}
Spacer()
Text("Likes")
}
.frame(height: 50)
.padding(.horizontal, 10)
HStack {
Rectangle()
.frame(width: self.underLineWidth, height: 2, alignment: .bottom)
.padding(.leading, leftPadding)
.animation(.basic())
Spacer()
}
}
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/BKtdn.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/BKtdn.jpg" alt=" "></a></p> | 56,661,706 | 7 | 3 | null | 2019-06-08 09:17:06.64 UTC | 39 | 2020-05-10 07:39:01.437 UTC | 2019-06-19 05:12:05.067 UTC | null | 1,994,390 | null | 6,610,681 | null | 1 | 56 | ios|swiftui | 41,507 | <p><strong><em>I have written a detailed explanation about using GeometryReader, view preferences and anchor preferences. The code below uses those concepts. For further information on how they work, check this article I posted: <a href="https://swiftui-lab.com/communicating-with-the-view-tree-part-1/" rel="noreferrer">https://swiftui-lab.com/communicating-with-the-view-tree-part-1/</a></em></strong></p>
<p>The solution below, will properly animate the underline:</p>
<p><a href="https://i.stack.imgur.com/XMtA9.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/XMtA9.gif" alt="enter image description here"></a></p>
<p>I struggled to make this work and I agree with you. Sometimes, you just need to be able to pass up or down the hierarchy, some framing information. In fact, the WWDC2019 session 237 (Building Custom Views with SwiftUI), explains that views communicate their sizing continuously. It basically says Parent proposes size to child, childen decide how they want to layout theirselves and communicate back to the parent. How they do that? I suspect the anchorPreference has something to do with it. However it is very obscure and not at all documented yet. The API is exposed, but grasping how those long function prototypes work... that's a hell I do not have time for right now.</p>
<p>I think Apple has left this undocumented to force us rethink the whole framework and forget about "old" UIKit habits and start thinking declaratively. However, there are still times when this is needed. Have you ever wonder how the background modifier works? I would love to see that implementation. It would explain a lot! I'm hoping Apple will document preferences in the near future. I have been experimenting with custom PreferenceKey and it looks interesting.</p>
<p>Now back to your specific need, I managed to work it out. There are two dimensions you need (the x position and width of the text). One I get it fair and square, the other seems a bit of a hack. Nevertheless, it works perfectly.</p>
<p>The x position of the text I solved it by creating a custom horizontal alignment. More information on that check session 237 (at minute 19:00). Although I recommend you watch the whole thing, it sheds a lot of light on how the layout process works.</p>
<p>The width, however, I'm not so proud of... ;-) It requires DispatchQueue to avoid updating the view while being displayed. <strong><em>UPDATE: I fixed it in the second implementation down below</em></strong></p>
<h2>First implementation</h2>
<pre class="lang-swift prettyprint-override"><code>extension HorizontalAlignment {
private enum UnderlineLeading: AlignmentID {
static func defaultValue(in d: ViewDimensions) -> CGFloat {
return d[.leading]
}
}
static let underlineLeading = HorizontalAlignment(UnderlineLeading.self)
}
struct GridViewHeader : View {
@State private var activeIdx: Int = 0
@State private var w: [CGFloat] = [0, 0, 0, 0]
var body: some View {
return VStack(alignment: .underlineLeading) {
HStack {
Text("Tweets").modifier(MagicStuff(activeIdx: $activeIdx, widths: $w, idx: 0))
Spacer()
Text("Tweets & Replies").modifier(MagicStuff(activeIdx: $activeIdx, widths: $w, idx: 1))
Spacer()
Text("Media").modifier(MagicStuff(activeIdx: $activeIdx, widths: $w, idx: 2))
Spacer()
Text("Likes").modifier(MagicStuff(activeIdx: $activeIdx, widths: $w, idx: 3))
}
.frame(height: 50)
.padding(.horizontal, 10)
Rectangle()
.alignmentGuide(.underlineLeading) { d in d[.leading] }
.frame(width: w[activeIdx], height: 2)
.animation(.linear)
}
}
}
struct MagicStuff: ViewModifier {
@Binding var activeIdx: Int
@Binding var widths: [CGFloat]
let idx: Int
func body(content: Content) -> some View {
Group {
if activeIdx == idx {
content.alignmentGuide(.underlineLeading) { d in
DispatchQueue.main.async { self.widths[self.idx] = d.width }
return d[.leading]
}.onTapGesture { self.activeIdx = self.idx }
} else {
content.onTapGesture { self.activeIdx = self.idx }
}
}
}
}
</code></pre>
<h2>Update: Better implementation without using DispatchQueue</h2>
<p>My first solution works, but I was not too proud of the way the width is passed to the underline view.</p>
<p>I found a better way of achieving the same thing. It turns out, the <strong>background</strong> modifier is very powerful. It is much more than a modifier that can let you decorate the background of a view.</p>
<p>The basic steps are:</p>
<ol>
<li>Use <code>Text("text").background(TextGeometry())</code>. TextGeometry is a custom view that has a parent with the same size as the text view. That is what .background() does. Very powerful.</li>
<li>In my implementation of <strong>TextGeometry</strong> I use GeometryReader, to get the geometry of the parent, which means, I get the geometry of the Text view, which means I now have the width.</li>
<li>Now to pass the width back, I am using <strong>Preferences</strong>. There's zero documentation about them, but after a little experimentation, I think preferences are something like "view attributes" if you like. I created my custom <strong>PreferenceKey</strong>, called <strong>WidthPreferenceKey</strong> and I use it in TextGeometry to "attach" the width to the view, so it can be read higher in the hierarchy.</li>
<li>Back in the ancestor, I use <strong>onPreferenceChange</strong> to detect changes in the width, and set the widths array accordingly.</li>
</ol>
<p>It may all sound too complex, but the code illustrates it best. Here's the new implementation:</p>
<pre class="lang-swift prettyprint-override"><code>import SwiftUI
extension HorizontalAlignment {
private enum UnderlineLeading: AlignmentID {
static func defaultValue(in d: ViewDimensions) -> CGFloat {
return d[.leading]
}
}
static let underlineLeading = HorizontalAlignment(UnderlineLeading.self)
}
struct WidthPreferenceKey: PreferenceKey {
static var defaultValue = CGFloat(0)
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
value = nextValue()
}
typealias Value = CGFloat
}
struct GridViewHeader : View {
@State private var activeIdx: Int = 0
@State private var w: [CGFloat] = [0, 0, 0, 0]
var body: some View {
return VStack(alignment: .underlineLeading) {
HStack {
Text("Tweets")
.modifier(MagicStuff(activeIdx: $activeIdx, idx: 0))
.background(TextGeometry())
.onPreferenceChange(WidthPreferenceKey.self, perform: { self.w[0] = $0 })
Spacer()
Text("Tweets & Replies")
.modifier(MagicStuff(activeIdx: $activeIdx, idx: 1))
.background(TextGeometry())
.onPreferenceChange(WidthPreferenceKey.self, perform: { self.w[1] = $0 })
Spacer()
Text("Media")
.modifier(MagicStuff(activeIdx: $activeIdx, idx: 2))
.background(TextGeometry())
.onPreferenceChange(WidthPreferenceKey.self, perform: { self.w[2] = $0 })
Spacer()
Text("Likes")
.modifier(MagicStuff(activeIdx: $activeIdx, idx: 3))
.background(TextGeometry())
.onPreferenceChange(WidthPreferenceKey.self, perform: { self.w[3] = $0 })
}
.frame(height: 50)
.padding(.horizontal, 10)
Rectangle()
.alignmentGuide(.underlineLeading) { d in d[.leading] }
.frame(width: w[activeIdx], height: 2)
.animation(.linear)
}
}
}
struct TextGeometry: View {
var body: some View {
GeometryReader { geometry in
return Rectangle().fill(Color.clear).preference(key: WidthPreferenceKey.self, value: geometry.size.width)
}
}
}
struct MagicStuff: ViewModifier {
@Binding var activeIdx: Int
let idx: Int
func body(content: Content) -> some View {
Group {
if activeIdx == idx {
content.alignmentGuide(.underlineLeading) { d in
return d[.leading]
}.onTapGesture { self.activeIdx = self.idx }
} else {
content.onTapGesture { self.activeIdx = self.idx }
}
}
}
}
</code></pre> |
23,838,857 | How to get hours difference between two dates | <p>I'm working for first time on Go, in this case i have a string on UTC format, I would like to know, how can I get the difference in hours between my date and the time now.
This is my current string</p>
<pre><code>v := "2014-05-03 20:57 UTC"
</code></pre> | 23,839,040 | 2 | 1 | null | 2014-05-23 21:55:54.387 UTC | 4 | 2019-05-21 20:24:17.237 UTC | 2019-05-21 20:24:17.237 UTC | null | 13,860 | null | 3,217,203 | null | 1 | 44 | time|go | 68,276 | <p>Use <a href="http://golang.org/pkg/time/#Parse">time.Parse</a> and <a href="http://golang.org/pkg/time/#Since">time.Since</a>:</p>
<pre><code>package main
import (
"fmt"
"time"
)
const (
// See http://golang.org/pkg/time/#Parse
timeFormat = "2006-01-02 15:04 MST"
)
func main() {
v := "2014-05-03 20:57 UTC"
then, err := time.Parse(timeFormat, v)
if err != nil {
fmt.Println(err)
return
}
duration := time.Since(then)
fmt.Println(duration.Hours())
}
</code></pre> |
48,196,706 | new URL() - WHATWG URL API | <p>I'm messing around with node and I'm trying to get an instance of the URL class (because of those handy properties). Like:</p>
<pre><code>const { URL } = require('url');
(...)
http.createServer((request,response) => {
let uri = new URL(request.url);
(...)
}
</code></pre>
<p>But it fails with</p>
<pre><code>TypeError [ERR_INVALID_URL]: Invalid URL: /
</code></pre>
<p>It's funny because </p>
<pre><code>const url = require('url');
url.parse();
</code></pre>
<p>works. So I got curious about it. I understand this later method is older.</p>
<p>I'm developing locally so to send a request I use localhost:8000 in the browser.</p>
<p>How do I use the information in <code>request</code> to instantiate a new URL object?</p>
<p>Info and things I've looked on already:</p>
<pre><code>node -v
v9.3.0
https://nodejs.org/api/url.html#url_class_url
https://stackoverflow.com/questions/44738065/uncaught-typeerror-url-is-not-a-constructor-using-whatwg-url-object-support-for
https://stackoverflow.com/questions/45047840/in-node-js-how-to-get-construct-url-string-from-whatwg-url-including-user-and-pa
https://stackoverflow.com/questions/47481784/does-url-parse-protect-against-in-a-url
https://stackoverflow.com/questions/17184791/node-js-url-parse-and-pathname-property
</code></pre> | 51,525,433 | 1 | 1 | null | 2018-01-10 21:52:52.893 UTC | 4 | 2022-06-15 10:59:06.577 UTC | 2018-01-15 22:54:46.227 UTC | null | 9,189,180 | null | 9,189,180 | null | 1 | 32 | javascript|node.js|server | 27,610 | <p>As Joshua Wise pointed out on Github (<a href="https://github.com/nodejs/node/issues/12682" rel="nofollow noreferrer">https://github.com/nodejs/node/issues/12682</a>), the problem is that <code>request.url</code> is NOT an absolute URL. It can be used as a path or relative URL, but it is missing the host and protocol.</p>
<p>Following the <a href="https://nodejs.org/api/url.html#new-urlinput-base" rel="nofollow noreferrer">API documentation</a>, you can construct a valid URL by supplying a base URL as the second argument. This is still awkward because the protocol is not easily available from <code>request.headers</code>. I simply assumed HTTP:</p>
<pre><code>var baseURL = 'http://' + request.headers.host + '/';
var myURL = new URL(request.url, baseURL);
</code></pre>
<p>This is obviously not an ideal solution, but at least you can take advantage of the query string parsing. For example,</p>
<pre><code>URL {
href: 'http://localhost:8080/?key1=value1&key2=value2',
origin: 'http://localhost:8080',
protocol: 'http:',
username: '',
password: '',
host: 'localhost:8080',
hostname: 'localhost',
port: '8080',
pathname: '/',
search: '?key1=value1&key2=value2',
searchParams: URLSearchParams { 'key1' => 'value1', 'key2' => 'value2' },
hash: '' }
</code></pre> |
25,554,504 | What does !*/ mean in .gitignore | <p>With git version 1.7.1, I'm trying to exclude all files except .php files.</p>
<p>The working solution I found relies on the command <code>!*/</code></p>
<pre><code># Ignore Everything
*
# Except these files
!.gitignore
!*/
!*.php
</code></pre>
<p>Without the <code>!*/</code>, it will only include the <code>*.php</code> files in the root directory. What is <code>!*/</code> doing that allows this to work?</p> | 25,554,628 | 2 | 1 | null | 2014-08-28 17:20:02.377 UTC | 2 | 2014-08-28 17:44:36.423 UTC | 2014-08-28 17:29:40.933 UTC | null | 1,064,767 | null | 456,645 | null | 1 | 30 | git|gitignore | 16,659 | <p>Take a look at the <a href="http://git-scm.com/docs/gitignore">documentation of gitignore</a></p>
<blockquote>
<p>An optional prefix "!" which negates the pattern; any matching file
excluded by a previous pattern will become included again. It is not
possible to re-include a file if a parent directory of that file is
excluded. Git doesn’t list excluded directories for performance
reasons, so any patterns on contained files have no effect, no matter
where they are defined. Put a backslash ("\") in front of the first
"!" for patterns that begin with a literal "!", for example,
"!important!.txt".</p>
</blockquote> |
20,572,309 | Detecting collisions in sprite kit | <p>I'm trying to make a simple game with sprite kit.
The basic idea is that there is one player who can jump to avoid blocks.
But i have a problem I don't know how to make it that when the player hits the block the player disappears and the blood animation starts.
First of all i don't understand what this code does that I found on apples website.</p>
<pre><code>static const uint32_t blockCategory = 0x1 <<0;
static const uint32_t playerCategory = 0x1 <<1;
</code></pre>
<p>Than i am calling the didBeginContact function and put a NSLOG("did call function") in it.
But i never receive the output in my debugger.</p>
<p>Here is my _player and _block code:
-(SKSpriteNode *)character {</p>
<pre><code>_player = [SKSpriteNode spriteNodeWithImageNamed:@"soldier_run1"];
_player.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:_player.size.width /2 -5];
_player.physicsBody.dynamic = YES;
_player.physicsBody.usesPreciseCollisionDetection = YES;
_player.physicsBody.friction = 0;
_player.physicsBody.categoryBitMask = playerCategory;
_player.physicsBody.collisionBitMask = blokCategory;
_player.name = @"player";
SKAction *animAction = [SKAction animateWithTextures:playerTextures timePerFrame:0.1 resize:YES restore:YES];
</code></pre>
<p>My _player code:</p>
<pre><code>[_player runAction:[SKAction repeatActionForever:animAction]];
return _player;
}
-(SKSpriteNode *)block {
_blok = [[SKSpriteNode alloc] initWithColor:[SKColor blackColor] size:CGSizeMake(15, 40)];
//physics
_blok.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:_blok.size];
_blok.physicsBody.dynamic = NO;
_blok.name = @"block";
_blok.physicsBody.categoryBitMask = blokCategory;
_blok.physicsBody.collisionBitMask = playerCategory;
SKAction *moveBlock = [SKAction sequence:@[
[SKAction moveToX:-20 duration:2] ]];
[_blok runAction:moveBlock ];
return _blok;
}
</code></pre>
<p>Also i don't really understand what the categoryBitMask and collisionBitMask do.
After i have that working i would like to make the character disappear from the screen and the blood animation to start, but I have no idea how to let that happen. I think you have to do something like:
if(_player && _block didcollide) {
}
But I don't know how to do it exactly.</p> | 20,604,762 | 2 | 1 | null | 2013-12-13 17:19:24.74 UTC | 9 | 2014-07-14 17:58:41.023 UTC | 2014-07-14 17:58:41.023 UTC | null | 759,866 | null | 2,708,696 | null | 1 | 17 | ios|objective-c|sprite-kit|collision | 17,248 | <p>The categoryBitMask sets the category that the sprite belongs to, whereas the collisionBitMask sets the category with which the sprite can collide with and not pass-through them.</p>
<p>For collision detection, you need to set the contactTestBitMask. Here, you set the categories of sprites with which you want the contact delegates to be called upon contact.</p>
<p>What you have already done is correct. Here are a few additions you need to do:</p>
<pre><code>_player.physicsBody.contactTestBitMask = blockCategory;
_blok.physicsBody.contactTestBitMask = playerCategory;
</code></pre>
<p>Afterwards, implement the contact delegate as follows:</p>
<pre><code>-(void)didBeginContact:(SKPhysicsContact *)contact`
{
NSLog(@"contact detected");
SKPhysicsBody *firstBody;
SKPhysicsBody *secondBody;
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
{
firstBody = contact.bodyA;
secondBody = contact.bodyB;
}
else
{
firstBody = contact.bodyB;
secondBody = contact.bodyA;
}
//Your first body is the block, secondbody is the player.
//Implement relevant code here.
}
</code></pre>
<p>For a good explanation on implementing collision detection, look at <a href="http://www.raywenderlich.com/51108/build-spaceinvaders-in-spritekit-part-2-of-2" rel="noreferrer">this</a> tutorial.</p> |
46,978,794 | Enable CORS in Spring 5 Webflux? | <p>How to enable <strong>CORS</strong> in a Spring 5 Webflux Project?</p>
<p>I cannot find any proper documentation.</p> | 49,571,895 | 8 | 2 | null | 2017-10-27 15:39:56.66 UTC | 13 | 2021-07-19 13:57:35.923 UTC | 2018-01-28 14:00:10.717 UTC | null | -1 | null | 7,432,865 | null | 1 | 29 | java|spring|cors|spring-webflux | 27,928 | <p>Here is another solution with the Webflux Configurer.</p>
<p>Side Note: Its Kotlin Code (copied from my project) but you can easily translate that to Java Code.</p>
<pre><code>@Configuration
@EnableWebFlux
class WebConfig: WebFluxConfigurer
{
override fun addCorsMappings(registry: CorsRegistry)
{
registry.addMapping("/**")
.allowedOrigins("*") // any host or put domain(s) here
.allowedMethods("GET, POST") // put the http verbs you want allow
.allowedHeaders("Authorization") // put the http headers you want allow
}
}
</code></pre> |
32,227,283 | Getting World Position from Depth Buffer Value | <p>I've been working on a deferred renderer to do lighting with, and it works quite well, albeit using a position buffer in my G-buffer. Lighting is done in world space.</p>
<p>I have tried to implement an algorithm to recreate the world space positions from the depth buffer, and the texture coordinates, albeit with no luck.</p>
<p>My vertex shader is nothing particularly special, but this is the part of my fragment shader in which I (attempt to) calculate the world space position:</p>
<pre><code>// Inverse projection matrix
uniform mat4 projMatrixInv;
// Inverse view matrix
uniform mat4 viewMatrixInv;
// texture position from vertex shader
in vec2 TexCoord;
... other uniforms ...
void main() {
// Recalculate the fragment position from the depth buffer
float Depth = texture(gDepth, TexCoord).x;
vec3 FragWorldPos = WorldPosFromDepth(Depth);
... fun lighting code ...
}
// Linearizes a Z buffer value
float CalcLinearZ(float depth) {
const float zFar = 100.0;
const float zNear = 0.1;
// bias it from [0, 1] to [-1, 1]
float linear = zNear / (zFar - depth * (zFar - zNear)) * zFar;
return (linear * 2.0) - 1.0;
}
// this is supposed to get the world position from the depth buffer
vec3 WorldPosFromDepth(float depth) {
float ViewZ = CalcLinearZ(depth);
// Get clip space
vec4 clipSpacePosition = vec4(TexCoord * 2.0 - 1.0, ViewZ, 1);
// Clip space -> View space
vec4 viewSpacePosition = projMatrixInv * clipSpacePosition;
// Perspective division
viewSpacePosition /= viewSpacePosition.w;
// View space -> World space
vec4 worldSpacePosition = viewMatrixInv * viewSpacePosition;
return worldSpacePosition.xyz;
}
</code></pre>
<p>I still have my position buffer, and I sample it to compare it against the calculate position later, so everything should be black: </p>
<pre><code>vec3 actualPosition = texture(gPosition, TexCoord).rgb;
vec3 difference = abs(FragWorldPos - actualPosition);
FragColour = vec4(difference, 0.0);
</code></pre>
<p>However, what I get is nowhere near the expected result, and of course, lighting doesn't work:</p>
<p><a href="https://i.stack.imgur.com/9Wypn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9Wypn.png" alt="image of issue"></a></p>
<p>(Try to ignore the blur around the boxes, I was messing around with something else at the time.)</p>
<p>What could cause these issues, and how could I get the position reconstruction from depth working successfully? Thanks.</p> | 32,246,825 | 1 | 4 | null | 2015-08-26 12:55:57.07 UTC | 9 | 2015-08-27 13:54:12.133 UTC | 2015-08-27 11:45:28.913 UTC | null | 219,515 | null | 219,515 | null | 1 | 12 | c++|opengl | 17,865 | <p>You are on the right track, but you have not applied the transformations in the correct order.</p>
<h3>A quick recap of what you need to accomplish here might help:</h3>
<ol>
<li><p>Given Texture Coordinates [<strong>0</strong>,<strong>1</strong>] and depth [<strong>0</strong>,<strong>1</strong>], calculate clip-space position</p>
<ul>
<li>Do <strong><em>not</em></strong> linearize the depth buffer</li>
<li>Output: <code>w</code> = <strong>1.0</strong> and <code>x,y,z</code> = [<strong>-w</strong>,<strong>w</strong>]</li>
</ul></li>
<li><p>Transform from clip-space to view-space (reverse projection)</p>
<ul>
<li>Use inverse projection matrix</li>
<li>Perform perspective divide</li>
</ul></li>
<li><p>Transform from view-space to world-space (reverse viewing transform)</p>
<ul>
<li>Use inverse view matrix</li>
</ul></li>
</ol>
<hr>
<h3>The following changes should accomplish that:</h3>
<pre><code>// this is supposed to get the world position from the depth buffer
vec3 WorldPosFromDepth(float depth) {
float z = depth * 2.0 - 1.0;
vec4 clipSpacePosition = vec4(TexCoord * 2.0 - 1.0, z, 1.0);
vec4 viewSpacePosition = projMatrixInv * clipSpacePosition;
// Perspective division
viewSpacePosition /= viewSpacePosition.w;
vec4 worldSpacePosition = viewMatrixInv * viewSpacePosition;
return worldSpacePosition.xyz;
}
</code></pre>
<p>I would consider changing the name of <code>CalcViewZ (...)</code> though, that is very much misleading. Consider calling it something more appropriate like <code>CalcLinearZ (...)</code>.</p> |
34,569,094 | What is the Angular equivalent to an AngularJS $watch? | <p>In AngularJS you were able to specify watchers to observe changes in scope variables using the <code>$watch</code> function of the <code>$scope</code>. What is the equivalent of watching for variable changes (in, for example, component variables) in Angular?</p> | 34,570,122 | 7 | 2 | null | 2016-01-02 18:13:09.827 UTC | 88 | 2020-02-26 10:40:59.187 UTC | 2020-02-26 10:40:59.187 UTC | null | 5,377,805 | null | 1,716,567 | null | 1 | 225 | angularjs|angular|watch|angular2-changedetection | 171,756 | <p>In Angular 2, change detection is automatic... <code>$scope.$watch()</code> and <code>$scope.$digest()</code> R.I.P.</p>
<p>Unfortunately, the Change Detection section of the dev guide is not written yet (there is a placeholder near the bottom of the <a href="https://angular.io/docs/ts/latest/guide/architecture.html" rel="noreferrer">Architecture Overview</a> page, in section "The Other Stuff").</p>
<p>Here's my understanding of how change detection works:</p>
<ul>
<li>Zone.js "monkey patches the world" -- it intercepts all of the asynchronous APIs in the browser (when Angular runs). This is why we can use <code>setTimeout()</code> inside our components rather than something like <code>$timeout</code>... because <code>setTimeout()</code> is monkey patched.</li>
<li>Angular builds and maintains a tree of "change detectors". There is one such change detector (class) per component/directive. (You can get access to this object by injecting <a href="https://angular.io/docs/ts/latest/api/core/index/ChangeDetectorRef-class.html" rel="noreferrer"><code>ChangeDetectorRef</code></a>.) These change detectors are created when Angular creates components. They keep track of the state of all of your bindings, for dirty checking. These are, in a sense, similar to the automatic <code>$watches()</code> that Angular 1 would set up for <code>{{}}</code> template bindings.<br>Unlike Angular 1, the change detection graph is a directed tree and cannot have cycles (this makes Angular 2 much more performant, as we'll see below).</li>
<li>When an event fires (inside the Angular zone), the code we wrote (the event handler callback) runs. It can update whatever data it wants to -- the shared application model/state and/or the component's view state.</li>
<li>After that, because of the hooks Zone.js added, it then runs Angular's change detection algorithm. By default (i.e., if you are not using the <code>onPush</code> change detection strategy on any of your components), every component in the tree is examined once (TTL=1)... from the top, in depth-first order. (Well, if you're in dev mode, change detection runs twice (TTL=2). See <a href="https://angular.io/docs/ts/latest/api/core/index/ApplicationRef-class.html#!#tick-anchor" rel="noreferrer">ApplicationRef.tick()</a> for more about this.) It performs dirty checking on all of your bindings, using those change detector objects.
<ul>
<li>Lifecycle hooks are called as part of change detection. <br>If the component data you want to watch is a primitive input property (String, boolean, number), you can implement <code>ngOnChanges()</code> to be notified of changes. <br>If the input property is a reference type (object, array, etc.), but the reference didn't change (e.g., you added an item to an existing array), you'll need to implement <code>ngDoCheck()</code> (see <a href="https://stackoverflow.com/a/34298708/215945">this SO answer</a> for more on this). <Br>You should only change the component's properties and/or properties of descendant components (because of the single tree walk implementation -- i.e., unidirectional data flow). Here's <a href="http://plnkr.co/edit/XWBSvE0NoQlRuOsXuOm0?p=preview" rel="noreferrer">a plunker</a> that violates that. Stateful pipes can also <a href="https://stackoverflow.com/questions/34456430/ngfor-doesnt-update-data-with-pipe-in-angular2/34497504#34497504">trip you up</a> here.</li>
</ul></li>
<li>For any binding changes that are found, the Components are updated, and then the DOM is updated. Change detection is now finished.</li>
<li>The browser notices the DOM changes and updates the screen.</li>
</ul>
<p>Other references to learn more:</p>
<ul>
<li><a href="https://blog.angularindepth.com/angulars-digest-is-reborn-in-the-newer-version-of-angular-718a961ebd3e" rel="noreferrer">Angular’s $digest is reborn in the newer version of Angular</a> - explains how the ideas from AngularJS are mapped to Angular</li>
<li><a href="https://blog.angularindepth.com/everything-you-need-to-know-about-change-detection-in-angular-8006c51d206f" rel="noreferrer">Everything you need to know about change detection in Angular</a> - explains in great detail how change detection works under the hood</li>
<li><a href="http://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html" rel="noreferrer">Change Detection Explained</a> - Thoughtram blog Feb 22, 2016 - probably the best reference out there</li>
<li>Savkin's <a href="https://www.youtube.com/watch?v=jvKGQSFQf10" rel="noreferrer">Change Detection Reinvented</a> video - definitely watch this one</li>
<li><a href="http://blog.jhades.org/how-does-angular-2-change-detection-really-work/" rel="noreferrer">How does Angular 2 Change Detection Really Work?</a>- jhade's blog Feb 24, 2016</li>
<li><a href="https://www.youtube.com/watch?v=3IqtmUscE_U" rel="noreferrer">Brian's video</a> and <a href="https://www.youtube.com/watch?v=V9Bbp6Hh2YE" rel="noreferrer">Miško's video</a> about Zone.js. Brian's is about Zone.js. Miško's is about how Angular 2 uses Zone.js to implement change detection. He also talks about change detection in general, and a little bit about <code>onPush</code>.</li>
<li>Victor Savkins blog posts: <a href="http://victorsavkin.com/post/110170125256/change-detection-in-angular-2" rel="noreferrer">Change Detection in Angular 2</a>, <a href="http://victorsavkin.com/post/114168430846/two-phases-of-angular-2-applications" rel="noreferrer">Two phases of Angular 2 applications</a>, <a href="http://victorsavkin.com/post/110170125256/change-detection-in-angular-2" rel="noreferrer">Angular, Immutability and Encapsulation</a>. He covers a lot of ground quickly, but he can be terse at times, and you're left scratching your head, wondering about the missing pieces.</li>
<li><a href="https://docs.google.com/document/d/1QKTbyVNPyRW-otJJVauON4TFMHpl0zNBPkJcTcfPJWg/edit" rel="noreferrer">Ultra Fast Change Detection</a> (Google doc) - very technical, very terse, but it describes/sketches the ChangeDetection classes that get built as part of the tree</li>
</ul> |
59,985,030 | Syntax error at: OPTIMIZE_FOR_SEQUENTIAL_KEY | <p>I created a table in Microsoft SQL Server Management Studio and the table worked fine, no errors while building.
Then i was copying the script to my project in visual studio when the following message showed:</p>
<blockquote>
<p>SQL80001: Incorrect syntax ner 'OPTIMIZE_FOR_SEQUENTIAL_KEY'</p>
</blockquote>
<p>I don't know why it happened, but this error was showing on this line of the code:</p>
<pre><code>(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF )
</code></pre>
<p>Do you guys know why the visual studio is showing that error message? How can I fix it?</p> | 59,985,394 | 3 | 2 | null | 2020-01-30 11:29:21.69 UTC | 3 | 2021-12-12 14:34:34.813 UTC | null | null | null | null | 12,320,917 | null | 1 | 37 | sql-server|visual-studio | 57,455 | <p>Make sure the target platform of your database project is SQL Server 2019 or Azure SQL Database, where the <code>OPTIMIZE_FOR_SEQUENTIAL_KEY</code> option was introduced. The syntax is not allowed in earlier versions.</p>
<p>Note <a href="https://techcommunity.microsoft.com/t5/sql-server/behind-the-scenes-on-optimize-for-sequential-key/ba-p/806888" rel="noreferrer">this Microsoft article</a> recommends judicious use of <code>OPTIMIZE_FOR_SEQUENTIAL_KEY = ON</code> even when keys are incremental. Relevant excerpt:</p>
<blockquote>
<p>If you're not experiencing the convoy phenomenon in your workload, you
may not see a huge benefit from this option, and you may even see a
slight degradation in performance due to the new flow control waits.
You should only use this option if you have a very heavily contentious
workload – one where the number of threads inserting into the index is
much higher than the number of schedulers – on a clustered index with
a sequential key (note that non-clustered indexes can experience this
problem as well, but because they have a smaller row size they don’t
have as high a tendency to form convoys so they are less likely to
benefit from this option).</p>
</blockquote> |
48,851,677 | How to direct vue-cli to put built project files in different directories? | <p>Maybe 8-9 months ago I created a Webpacked Vue.js project with vue-cli and was able to modify <code>/build/webpack.dev.conf.js</code> to have it put the "compiled" <code>index.html</code> and JavaScript / CSS files in the right folders in my Flask app when I run <code>npm run build</code>.</p>
<p>I am now showing someone else how to create a Vue.js / Flask app and I see that the way vue-cli works seems to have changed, so that I no longer have access to the <code>/build/</code> folder.</p>
<p>I read the docs and <a href="https://github.com/vuejs/vue-cli/blob/dev/docs/webpack.md" rel="noreferrer">they seemed to say</a> that it now abstracts away the Webpack config ("<em>Since @vue/cli-service abstracts away the webpack config...</em>"), but that if I want to see Webpack's config options, I can do <code>vue inspect > output.js</code>. I did that and don't see the entries in there that I changed when I did this eight months ago:</p>
<p><code>/build/webpack.prod.conf.js</code>:</p>
<pre><code>new HtmlWebpackPlugin({
filename: process.env.NODE_ENV === 'testing'
- ? 'index.html'
+ ? 'app.html'
: config.build.index,
- template: 'index.html',
+ template: 'app.html',
</code></pre>
<p><code>/build/webpack.dev.conf.js</code>:</p>
<pre><code>new HtmlWebpackPlugin({
- filename: 'index.html',
- template: 'index.html',
+ filename: 'app.html',
+ template: 'app.html',
</code></pre>
<p><code>/config/index.js</code>:</p>
<pre><code>module.exports = {
build: {
env: require('./prod.env'),
- index: path.resolve(__dirname, '../dist/index.html'),
- assetsRoot: path.resolve(__dirname, '../dist'),
- assetsSubDirectory: 'static',
- assetsPublicPath: '/',
+ index: path.resolve(__dirname, '../../server/templates/app.html'),
+ assetsRoot: path.resolve(__dirname, '../../server/static/app'),
+ assetsSubDirectory: '',
+ assetsPublicPath: '/static/app',
</code></pre>
<p>It looks like the <code>vue build</code> command-line command can accept an argument that allows you to specify the output directory, but I need to specify two different directories: one for the HTML file (which should live in Flask's <code>/templates/</code> folder), and another for the JavaScript / CSS code (which should go in Flask's <code>/static/</code> folder).</p> | 53,349,027 | 6 | 4 | null | 2018-02-18 12:29:03.2 UTC | 15 | 2021-01-05 09:54:11.927 UTC | 2018-02-18 14:05:09.51 UTC | null | 4,115,031 | null | 4,115,031 | null | 1 | 59 | vue.js|vue-cli | 76,040 | <p>I just had to do this for a new project using the latest Vue-CLI and it was pretty simple: I just needed to have a file called <code>vue.config.js</code> at the top-level of my Vue project and within it I needed the following code:</p>
<pre><code>const path = require("path");
module.exports = {
outputDir: path.resolve(__dirname, "../backend/templates/SPA"),
assetsDir: "../../static/SPA"
}
</code></pre>
<p><strong>Warning: Vue-CLI will delete the contents of whatever folders you specify to use for its output.</strong> To get around this, I created the "SPA" folders within my <code>templates/</code> and <code>static/</code> directories.</p>
<p>Note also that the <code>assetsDir</code> is specified relative to the <code>outputDir</code>.</p> |
48,778,619 | Node/Express - Refused to apply style because its MIME type ('text/html') | <p>I've been having this issue for the past couple of days and can't seem to get to the bottom of this. We doing a very basic node/express app, and are trying to serve our static files using something like this:</p>
<pre><code>app.use(express.static(path.join(__dirname, "static")));
</code></pre>
<p>This does what I expect it to for the most part. We have a few folders in our static folder for our css and javascript. We're trying to load our css into our EJS view using this static path:</p>
<pre><code><link rel="stylesheet" type="text/css" href="/css/style.css">
</code></pre>
<p>When we hit our route <code>/</code>, we're getting all of the content but our CSS is not loading. We're getting this error in particular:</p>
<blockquote>
<p>Refused to apply style from '<a href="http://localhost:3000/css/style.css" rel="noreferrer">http://localhost:3000/css/style.css</a>'
because its MIME type ('text/html') is not a supported stylesheet MIME
type, and strict MIME checking is enabled.</p>
</blockquote>
<h2>What I've tried:</h2>
<ol>
<li>Clear NPM Cache / Fresh Install
<ul>
<li><code>npm verify cache</code></li>
<li><code>rm -rf node_modules</code></li>
<li><code>npm install</code></li>
</ul></li>
<li>Clear Browser Cache</li>
<li>Various modifications to folder names and references to that</li>
<li>Adding/removing forward slashes form the href</li>
<li>Moving the css folder into the root and serving it from there</li>
<li>Adding/removing slashes from <code>path.join(__dirname, '/static/')</code></li>
<li>There was a comment about a service worker possibly messing things up in a github issue report, and seemed to fix a lot of people's problems. There is no service worker for our localhost: <a href="https://github.com/facebook/create-react-app/issues/658" rel="noreferrer">https://github.com/facebook/create-react-app/issues/658</a>
<ul>
<li>We're not using react, but I'm grasping at any google search I can find</li>
</ul></li>
</ol>
<h2>The route:</h2>
<pre><code>app.get("/", function(req, res) {
res.render("search");
});
</code></pre>
<h2>The view:</h2>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Search for a Movie</title>
<link rel="stylesheet" type="text/css" href="/static/css/style.css">
</head>
<body>
<h1>Search for a movie</h1>
<form method="POST" action="/results">
<label for="movie-title">Enter a movie title:</label><br>
<input id="movie-title" type="text" name="title"><br>
<input type="submit" value="Submit Search">
</form>
</body>
</html>
</code></pre>
<h2>The package.json:</h2>
<pre><code>{
"name": "express-apis-omdb",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "nodemon index.js",
"lint:js": "node_modules/eslint/bin/eslint.js ./ ./**/*.js --fix; exit 0",
"lint:css": "node_modules/csslint/cli.js public/css/; exit 0"
},
"license": "ISC",
"devDependencies": {
"babel-eslint": "^6.0.4",
"csslint": "^0.10.0",
"eslint": "^2.11.1",
"eslint-config-airbnb": "^9.0.1",
"eslint-plugin-import": "^1.8.1",
"eslint-plugin-jsx-a11y": "^1.3.0",
"eslint-plugin-react": "^5.1.1"
},
"dependencies": {
"body-parser": "^1.18.2",
"dotenv": "^5.0.0",
"ejs": "^2.5.7",
"express": "^4.13.4",
"morgan": "^1.7.0",
"path": "^0.12.7",
"request": "^2.83.0"
}
}
</code></pre>
<h2>The project structure:</h2>
<pre><code>-app
--node_modules
--static
---img
---css
---js
--views
---movie.ejs
---results.ejs
---search.ejs
--index.js
--package-lock.json
--package.json
</code></pre>
<p><strong>Note:</strong> We are currently not using a layout file for our EJS. </p>
<p>I'm happy to provide additional details if needed.</p> | 48,792,698 | 7 | 5 | null | 2018-02-14 02:08:55.32 UTC | 6 | 2021-05-23 23:57:36.147 UTC | null | null | null | null | 5,273,239 | null | 1 | 19 | node.js|express|mime-types|static-files | 42,605 | <p>The problem is the result of an improperly named file. Our student had a space at the end of the <code>style.css</code> file. There were a few tip offs to this, the first was a lack of syntax highlighting in the text editor, and the second was the text editor detecting the filetype for other newly created css files but not the improperly named file. Removing the space resolved the issue.</p>
<p>Thank you slebetman for your help in pointing me in the right direction. </p> |
20,335,967 | How useful/important is REST HATEOAS (maturity level 3)? | <p>I'm getting involved in a project where some senior team members believe that a REST API has to be HATEOAS compliant and implement all Richardson's maturity levels (<a href="http://martinfowler.com/articles/richardsonMaturityModel.html">http://martinfowler.com/articles/richardsonMaturityModel.html</a>)!</p>
<p>AFAIK most REST implementations are not HATEOAS compliant and there should be a good reason why more people aren't doing it. I can think of reasons like added complexity, lack of frameworks (server and client sides), performance concern and...</p>
<p>What do you think? Have you had any experience with HATEOAS in a real world project?</p> | 20,336,307 | 5 | 1 | null | 2013-12-02 19:11:23.22 UTC | 61 | 2021-09-17 19:14:17.827 UTC | 2021-09-17 19:14:17.827 UTC | null | 6,862,601 | null | 1,068,828 | null | 1 | 142 | rest|hateoas | 26,121 | <p>Nobody in the REST community says REST is easy. <strong>HATEOAS</strong> is just one of the aspects that adds difficulty to a REST architecture.</p>
<p>People don't do HATEOAS for all the reasons you suggest: it's difficult. It adds complexity to both the server-side and the client (if you actually want to benefit from it).</p>
<p>HOWEVER, billions of people experience the benefits of REST today. Do you know what the "<strong>checkout</strong>" <em>URL is at Amazon?</em> I don't. Yet, I can checkout every day. Has that URL changed? I don't know it, I don't care.</p>
<p>Do you know who does care? Anyone who's written a screen-scraped Amazon automated client. Someone who has likely painstakingly sniffed web traffic, read HTML pages, etc. to find what links to call when and with what payloads.</p>
<p>And as soon as Amazon changed their internal processes and URL structure, those hard-coded clients failed -- because the links broke.</p>
<p>Yet, the casual web surfers were able to shop all day long with hardly a hitch.</p>
<p>That's REST in action, it's just augmented by the human being that is able to interpret and intuit the text-based interface, recognize a small graphic with a shopping cart, and suss out what that actually means.</p>
<p>Most folks writing software don't do that. Most folks writing automated clients don't care. Most folks find it easier to fix their clients when they break than engineer the application to not break in the first place. Most folks simply don't have enough clients where it matters.</p>
<p>If you're writing an internal API to communicate between two systems with expert tech support and IT on both sides of the traffic, who are able to communicate changes quickly, reliably, and with a schedule of change, then REST buys you nothing. You don't need it, your app isn't big enough, and it's not long-lived enough to matter.</p>
<p>Large sites with large user bases do have this problem. They can't just ask folks to change their client code on a whim when interacting with their systems. The server's development schedule is not the same as the client development schedule. Abrupt changes to the API are simply unacceptable to everyone involved, as it disrupts traffic and operations on both sides.</p>
<p>So, an operation like that would very likely benefit from HATEOAS, as it's easier to version, easier for older clients to migrate, easier to be backward compatible than not.</p>
<p>A client that delegates much of its workflow to the server and acts upon the results is much more robust to server changes than a client that does not.</p>
<p>But most folks don't need that flexibility. They're writing server code for 2 or 3 departments, it's all internal use. If it breaks, they fix it, and they've factored that into their normal operations.</p>
<p>Flexibility, whether from REST or anything else, breeds complexity. If you want it simple, and fast, then you don't make it flexible, you "just do it", and be done. As you add abstractions and dereferencing to systems, then stuff gets more difficult, more boilerplate, more code to test.</p>
<p>Much of REST fails the "you're not going to need it" bullet point. Until, of course, you do.</p>
<p>If you need it, then use it, and use it as it's laid out. REST is not shoving stuff back and forth over HTTP. It never has been, it's a much higher level than that.</p>
<p>But when you do need REST, and you do use REST, then HATEOAS is a necessity. It's part of the package and a key to what makes it work at all.</p>
<p><strong>Example:-</strong> To understand it better let’s look at the below response of retrieve user with id 123 from the server (<code>http://localhost:8080/user/123</code>):</p>
<pre><code>{
"name": "John Doe",
"links": [{
"rel": "self",
"href": "http://localhost:8080/user/123"
},
{
"rel": "posts",
"href": "http://localhost:8080/user/123/post"
},
{
"rel": "address",
"href": "http://localhost:8080/user/123/address"
}
]
}
</code></pre> |
6,346,001 | Why are there no ||= or &&= operators in C#? | <p>We have equivalent assignment operators for all Logical operators, Shift operators, Additive operators and all Multiplicative operators.</p>
<p>Why did the logical operators get left out?
Is there a good technical reason why it is hard?</p> | 6,346,266 | 2 | 3 | null | 2011-06-14 15:23:08.853 UTC | 2 | 2020-11-11 07:29:46.133 UTC | 2017-11-15 23:53:19.963 UTC | null | 2,436,175 | null | 593,627 | null | 1 | 69 | c#|operators|language-design|assignment-operator|compound-assignment | 14,730 | <blockquote>
<p>Why did the logical operators get left out? Is there a good technical reason why it is hard?</p>
</blockquote>
<p><strong>They didn't</strong>. You can do <code>&=</code> or <code>|=</code> or <code>^=</code> if you want.</p>
<pre><code>bool b1 = false;
bool b2 = true;
b1 |= b2; // means b1 = b1 | b2
</code></pre>
<p>The <code>||</code> and <code>&&</code> operators do not have a compound form because frankly, they're a bit silly. Under what circumstances would you want to say</p>
<pre><code>b1 ||= b2;
b1 &&= b2;
</code></pre>
<p>such that the right hand side is not evaluated if the left hand side does not change? It seems like only a few people would actually use this feature, so why put it in?</p>
<p>For more information about the compound operators, see my serious article here:<br />
<a href="https://docs.microsoft.com/en-us/archive/blogs/ericlippert/compound-assignment-part-one" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/archive/blogs/ericlippert/compound-assignment-part-one</a></p>
<p>and the follow-up April-Fools article here:<br />
<a href="https://docs.microsoft.com/en-us/archive/blogs/ericlippert/compound-assignment-part-two" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/archive/blogs/ericlippert/compound-assignment-part-two</a></p> |
57,727,372 | How do I get the value of a tensor in PyTorch? | <p>Printing a tensor <code>x</code> gives:</p>
<pre><code>>>> x = torch.tensor([3])
>>> print(x)
tensor([3])
</code></pre>
<p>Indexing <code>x.data</code> gives:</p>
<pre><code>>>> x.data[0]
tensor(3)
</code></pre>
<p>How do I get just a regular non-tensor value <code>3</code>?</p> | 57,727,748 | 4 | 1 | null | 2019-08-30 13:08:12.813 UTC | 15 | 2022-07-11 08:46:12.847 UTC | 2022-07-11 08:46:12.847 UTC | null | 365,102 | null | 10,855,529 | null | 1 | 76 | python|pytorch|tensor | 113,079 | <p>You can use <a href="https://pytorch.org/docs/stable/generated/torch.Tensor.item.html" rel="noreferrer"><code>x.item()</code></a> to get a Python number from a <code>Tensor</code> that has one element.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.