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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
56,509,640 | How to set custom highlighted state of SwiftUI Button | <p>I have a Button. I want to set custom background color for highlighted state. How can I do it in SwiftUI?</p>
<p><a href="https://i.stack.imgur.com/9aYkU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9aYkU.png" alt="enter image description here"></a></p>
<pre><code>Button(action: signIn) {
Text("Sign In")
}
.padding(.all)
.background(Color.red)
.cornerRadius(16)
.foregroundColor(.white)
.font(Font.body.bold())
</code></pre> | 56,980,172 | 6 | 0 | null | 2019-06-08 19:48:44.633 UTC | 15 | 2022-06-02 07:01:33.18 UTC | null | null | null | null | 4,106,171 | null | 1 | 42 | swiftui | 34,505 | <h3>Updated for SwiftUI beta 5</h3>
<p>SwiftUI does actually <a href="https://developer.apple.com/documentation/swiftui/buttonstyle" rel="noreferrer">expose an API</a> for this: <code>ButtonStyle</code>.</p>
<pre class="lang-swift prettyprint-override"><code>struct MyButtonStyle: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.padding()
.foregroundColor(.white)
.background(configuration.isPressed ? Color.red : Color.blue)
.cornerRadius(8.0)
}
}
// To use it
Button(action: {}) {
Text("Hello World")
}
.buttonStyle(MyButtonStyle())
</code></pre> |
28,771,558 | Set dbpath in MongoDB homebrew installed (Mac OS) | <p>Hello I installed Mongodb via Homebrew.
On Mac OS Yosemite.
MongoDB shell version: 2.6.8</p>
<p>What I want to achieve is to not have to every time put the <strong>--dbpath /path...</strong> everytime but just <strong>mongod</strong></p>
<p>Now I have to write:</p>
<pre><code>mongod --dbpath /usr/local/var/mongodb/
</code></pre>
<p>It works fine.</p>
<p>My problem is that when I try to begin mongod with:</p>
<pre><code>mongod --config /usr/local/etc/mongod.conf
</code></pre>
<p>It does nothing. Is that normal?</p>
<p>My config file is:</p>
<pre>
systemLog:
destination: file
path: /usr/local/var/log/mongodb/mongo.log
logAppend: true
storage:
dbPath: /usr/local/var/mongodb
net:
bindIp: 127.0.0.1
</pre>
<p>Is there a way to create a config file that mongo reads automatically so I can run <strong>mongod</strong> without extra parameters? </p>
<p>Or a way to set the dbpath to /usr/local/var/mongodb by default?</p> | 28,771,856 | 2 | 0 | null | 2015-02-27 18:07:08.657 UTC | 10 | 2017-11-09 01:57:20.777 UTC | null | null | null | null | 3,509,206 | null | 1 | 20 | mongodb|homebrew | 13,965 | <p>I also installed MongoDB using Homebrew and simply added the following to my <code>.bash_profile</code>.</p>
<pre><code># MongoDB Aliases
alias mongod="mongod --config /usr/local/etc/mongod.conf --fork"
</code></pre>
<p>So every time I run <code>mongod</code> in the terminal, it reads from the configuration file and forks the process.</p> |
28,405,621 | What is the syntax and semantics of the `where` keyword? | <p>Unfortunately, Rust's documentation regarding <code>where</code> is very lacking. The keyword only appears in one or two unrelated examples in the reference.</p>
<ol>
<li><p>What semantic difference does <code>where</code> make in the following code? Is there any difference at all? Which form is preferred?</p>
<pre><code>fn double_a<T>(a:T) -> T where T:std::num::Int {
a+a
}
fn double_b<T: std::num::Int>(a:T) -> T {
a+a
}
</code></pre></li>
<li><p>In the implementation of the CharEq trait, it seems that <code>where</code> is being used as some sort of "selector" to implement Trait for anything that matches some closure type. Am I correct?</p></li>
</ol>
<p>Is there any way I can get a better, more complete picture of <code>where</code>? (full specification of usage and syntax)</p> | 28,407,025 | 1 | 0 | null | 2015-02-09 08:33:49.843 UTC | 4 | 2015-02-10 01:16:30.69 UTC | 2015-02-10 01:16:30.69 UTC | null | 155,423 | null | 4,523,058 | null | 1 | 31 | rust | 10,416 | <p>In your example, the two codes are strictly equivalent.</p>
<p>The <code>where</code> clauses were introduced to allow more expressive bound-checking, doing for example :</p>
<pre><code>fn foo<T>(a: T) where Bar<T>: MyTrait { /* ... */ }
</code></pre>
<p>Which is not possible using only the old syntax.</p>
<p>Using <code>where</code> rather than the original syntax is generally preferred for readability even if the old syntax can still be used.</p>
<p>You can imagine for example constructions like</p>
<pre><code>fn foo<A, B, C>(a: A, b: B, c: C)
where A: SomeTrait + OtherTrait,
B: ThirdTrait<A>+ OtherTrait,
C: LastTrait<A, B>
{
/* stuff here */
}
</code></pre>
<p>which are much more readable this way, even if the could still be expressed using the old syntax.</p>
<p>For your question about the <code>CharEq</code> trait, the code is:</p>
<pre><code>impl<F> CharEq for F where F: FnMut(char) -> bool {
#[inline]
fn matches(&mut self, c: char) -> bool { (*self)(c) }
#[inline]
fn only_ascii(&self) -> bool { false }
}
</code></pre>
<p>It literally means: Implementation of trait <code>CharEq</code> for all type <code>F</code> that already implements the trait <code>FnMut(char) -> bool</code> (that is, a closure or a function taking a <code>char</code> and returning a <code>bool</code>).</p>
<p>For more details, you can look at the RFC that introduced the <code>where</code> clauses : <a href="https://github.com/rust-lang/rfcs/pull/135" rel="noreferrer">https://github.com/rust-lang/rfcs/pull/135</a></p> |
40,562,031 | Webpack: how does Webpack work internally? | <p>As far as I could understand, Webpack is a tool for organizing assets in the project. However, I don't understand how it works internally and it seems a bit magical.</p>
<ul>
<li>Is there some kind of runtime engine resolving modules or dependencies?</li>
<li>Does it run on the server or in the client browser?
<ul>
<li>If it runs on the server, does it have to run on a some kind of <code>webpack-*-server</code>?</li>
<li>If it runs in the browser, how does it build module <-> loader <-> map? How is it sent to the browser?</li>
</ul></li>
</ul> | 42,065,159 | 1 | 6 | null | 2016-11-12 10:44:50.15 UTC | 29 | 2020-04-10 10:34:25.72 UTC | 2019-11-10 20:33:37.983 UTC | null | 4,617,687 | null | 3,227,319 | null | 1 | 49 | webpack | 24,225 | <p><em><strong>Webpack - The Why and the How</strong></em></p>
<p>Don't let yourself get confused by all the fancy stuff Webpack does.
What is Webpack then? Well its a module bundler, there we go. Just kidding, this doesn't tell the beginner very much at all. I believe that the why is important to <em>getting</em> webpack so the bulk of this answer will focus on that.</p>
<p>At its core Webpack allows us to use javascript modules within our browser by taking multiple files and assets and combining them into one big file as shown below in this image from the new docs for <a href="https://webpack.js.org/" rel="noreferrer">Webpack 2</a>.</p>
<p><a href="https://i.stack.imgur.com/QjanT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QjanT.png" alt="Overview of Webpack" /></a></p>
<p>All the extra shiny things such as compiling es6/7 to es5 or allowing us to use css modules are just nice <em>extras</em> afforded to us by Webpack.</p>
<p>The powerful ecosystem of Webpack plugins and extras makes Webpack seem confusing as it appears to do so much. While the additional features afforded to us through plugins is great we need to stay focused on the core reason Webpack exists - <em>module bundling</em>. Therefore loaders and plugins are outside the scope of this high level discussion on the fundamental problem that Webpack helps solve.</p>
<p><strong>Webpack is a command line tool to create bundles of assets (code and files). Webpack doesn't run on the server or the browser. Webpack takes all your javascript files and any other assets and transforms then into one huge file.</strong></p>
<p>This big file can then be sent by the server to a client's browser.
Remember the browser and server don't care that this big file was generated using Webpack it just treats it like any other file.</p>
<p><strong>webpack-dev-server vs webpack cli</strong></p>
<p><em>webpack-dev-server is a fundamentally different tool from the webpack cli</em> (command line tool) described above. It is a development server that runs on node / express. When this server is running we load our app from one of the ports on this development server and we can access additional features while developing our app that makes our life easier such as hot module reloading and autobundling (runs webpack cli to bundle automatically when a file changes). The advantage of hot module reloading is that we can keep the app running and inject new versions of the files that are edited during runtime. Therefore we can see what changes to some files in the application look like without losing the state of the whole app.</p>
<p><em><strong>The Why</strong></em></p>
<p><strong>Traditional Server Rendered Apps</strong></p>
<p>Traditionally apps have been server side rendered. This means that a request is made by a client to a server and all the logic is on the server. The server spits out a static html page back to the client which is what they see in their browser. This is why whenever you navigate in old server-side rendered apps you will see the page flash as it refreshes.</p>
<p><strong>Single Page Apps - SPAs</strong></p>
<p>However nowadays single page applications are all the rage. On a single page application our app is windowed within one url and we never need to refresh. This is considered a nicer experience for the user as it feels slicker not having to refresh. In SPAs if we want to navigate from the home to say the signin page we would navigate to the url for the signin page. However unlike traditional server side rendered pages when the client's browser makes this request the page will not refresh. Instead the app will dynamically update itself in order to show the signin content. Although this looks like a separate page in our Single Page Application our app just dynamically updates for different pages.</p>
<p><strong>Dynamic SPAs mean more code in the browser</strong></p>
<p>So in SPAs with all this dynamic content there is way more javascript code that is in the browser. When we say dynamic we are referring to the amount of logic that lives within the client's browser in the form of javascript. Our server side rendered apps spit out static pages that are not dynamic. The dynamism all happens in the server while generating the static page but once it hits the browser it is relatively static (there isn't a lot of javascript in it)</p>
<p><em><strong>The How</strong></em></p>
<p><strong>Managing this new abundance of browser logic i.e more Javascript</strong></p>
<p>Webpack was primarily designed to deal with the emerging trend of having more and more javascript in the client.</p>
<p>Ok, so what we have a lot of javascript in the browser why is this a problem?</p>
<p><strong>We need to split the code into multiple files on the client so the app is easier to work on</strong></p>
<p>Well, where do we put it all? We can put it all in one big file. However, if we do this it will be a nightmare to wade through it and understand how all the parts work. Instead, we need to split this one huge chunk of code into smaller chunks according to the function of each chunk - i.e splitting the code across multiple files.</p>
<p>As you probably know decomposing large things into smaller things grouped by function is what we mean when we talk about 'making something modular'. You may be thinking why not just split the big chunk of code into little chunks and be done with it. The problem is the client doesn't magically know which files import stuff from other files. So we could have multiple isolated files without Webpack but <strong>the app won't work properly as it is more likely than not that within the big chunk of code most of the code within it will rely on other parts of code in the big chunk to work</strong>.</p>
<p>We need something like Webpack or one of its alternatives (browserify) to create a module system. <strong>On the server side Node has a built-in module resolver where you can "require" modules. However browsers do not come with this functionality.</strong></p>
<p>However if we have multiple files some will import from each other and we need a way of knowing which files rely or are <strong>dependent</strong> on each other. Webpack allows us to use JavaScript modules on the front end by traversing through the files from an <strong>entry point</strong> and then mapping their dependencies. <strong>Think of the entry point as the top of the hierarchy in a chain of files that are dependent on each other.</strong></p>
<p><strong>Module/ Dependency resolution in Webpack</strong></p>
<p>By mapping out a graph of the dependencies Webpack is able to load the different modules in the correct order asynchronously and in parallel. Internally Webpack has its own resolver for figuring out the dependency graph between different modules. The webpack docs state that</p>
<blockquote>
<p>The resolver helps webpack finds the module code that needs to be
included in the bundle for every such require/import statement.</p>
</blockquote>
<p>Then the docs explain that the resolver takes a different approach according to the type of path that is referenced by imports in the files that Webpack is bundling.</p>
<blockquote>
<p>The resolving process is pretty simple and distinguishes between three
types of requests:</p>
<ul>
<li>absolute path: require("/home/me/file"), require("C:\Home\me\file")</li>
<li>relative path: require("../src/file"), require("./file") module path:</li>
<li>require("module"), require("module/lib/file")</li>
</ul>
</blockquote> |
37,487,283 | Firebase 3.x - Token / Session Expiration | <p>Does anyone know how long would it take for the token to expire? There no option now to set the token validity on the console. </p> | 37,487,617 | 4 | 0 | null | 2016-05-27 15:29:14.417 UTC | 10 | 2020-10-26 17:48:59.42 UTC | 2016-06-09 10:23:41.287 UTC | null | 4,065,019 | null | 4,065,019 | null | 1 | 48 | session|firebase|token|firebase-authentication | 41,418 | <p>In the latest release of Firebase Authentication, login sessions don't expire anymore. Instead it uses a combination of long-lived account tokens and short-lived, auto-refreshed access tokens to get the best of both worlds.</p>
<p>If you want to end a user's session, you can call <a href="https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseAuth.html#exceptions_5"><code>signOut()</code></a>.</p> |
873,200 | Memory management and performSelectorInBackground: | <p>Which is right? This:</p>
<pre><code>NSArray* foo = [[NSArray alloc] initWithObjects:@"a", @"b", nil];
[bar performSelectorInBackground:@selector(baz:) withObject:foo];
- (void)baz:(NSArray*)foo {
...
[foo release];
}
</code></pre>
<p>Or:</p>
<pre><code>NSArray* foo = [[[NSArray alloc] initWithObjects:@"a", @"b", nil] autorelease];
[bar performSelectorInBackground:@selector(baz:) withObject:foo];
- (void)baz:(NSArray*)foo {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
...
[pool release];
}
</code></pre>
<p>I know the first one works, but Clang complains about it, so I wonder if there's a better pattern to use.</p>
<p>I would "just try out" the 2nd one, but with autoreleasing, who knows whether the absence of <code>EXC_BAD_ACCESS</code> means that you're doing it right or that you just got lucky...</p> | 873,293 | 2 | 0 | null | 2009-05-16 20:18:02.17 UTC | 12 | 2011-10-29 10:01:54.83 UTC | null | null | null | null | 56,817 | null | 1 | 12 | objective-c|iphone|cocoa-touch | 22,637 | <p>First is wrong. </p>
<p>performSelectorInBackground:withObject: retains both bar and foo until task is performed. Thus, you should autorelease foo when you create it and let performSelectorInBackground:withObject take care of the rest. See <a href="http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/performSelectorInBackground:withObject:" rel="noreferrer">documentation</a></p>
<p>Latter is correct because you autorelease foo when you create it. Autorelease pool that you create inside baz has nothing do with correctness of foo's memory management. That autorelease pool is needed for autoreleased objects <strong>inside</strong> pool allocation and release in baz, it doesn't touch foo's retain count at all. </p> |
1,280,704 | How can I sort a ListBox using only XAML and no code-behind? | <p>I need to sort the strings in a <code>ListBox</code>, but it is bound to the view model by another component via the <code>DataContext</code>. So I can't directly instantiate the view model in XAML, as in <a href="http://www.galasoft.ch/mydotnet/articles/article-2007081301.aspx" rel="noreferrer">this example</a>, which uses the <code>ObjectDataProvider</code>.</p>
<p>In my XAML:</p>
<pre><code><ListBox ItemsSource="{Binding CollectionOfStrings}" />
</code></pre>
<p>In my view model:</p>
<pre><code>public ObservableCollection<string> CollectionOfStrings
{
get { return collectionOfStrings; }
}
</code></pre>
<p>In another component:</p>
<pre><code>view.DataContext = new ViewModel();
</code></pre>
<p>There is no code behind! So using purely XAML, how would I sort the items in the ListBox? Again, the XAML doesn't own the instantiation of the view model.</p> | 1,280,768 | 2 | 0 | null | 2009-08-14 23:44:43.533 UTC | 15 | 2021-06-03 06:57:03.183 UTC | 2012-09-05 05:53:08.677 UTC | null | 46,027 | null | 46,027 | null | 1 | 41 | wpf|xaml|sorting|mvvm|listbox | 32,242 | <p>Use a <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.collectionviewsource.aspx" rel="noreferrer"><code>CollectionViewSource</code></a>:</p>
<pre><code><CollectionViewSource x:Key="SortedItems" Source="{Binding CollectionOfStrings}"
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="SomePropertyOnYourItems"/>
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
<ListBox ItemsSource="{Binding Source={StaticResource SortedItems}}"/>
</code></pre>
<p>You might want to wrap your strings in a custom VM class so you can more easily apply sorting behavior.</p> |
879,011 | Is it possible to change emacs' regexp syntax? | <p>I love emacs. I love regexs. I hate emacs' regex syntax - the need to escape grouping parens and braces, that you <em>dont</em> escape literal parens, the lack of predefined character classes, etc.</p>
<p>Can I replace emacs' regex engine, or tweak some setting, so that when I use the Query-replace-regexp (or one of many other) feature I can use the syntax I program with in java/js/perl/ruby/etc...?</p>
<p><strong>Edit:</strong>
The subject was originally "how to change emacs' regex engine" which would not only change escaping rules and add character classes, but also (not mentioned in the post) add support for various common extensions (?...). Features like non-capturing parens: (?:...), match only if/if-not followed by: (?=...)/(?!...), and others. I don't believe (though happy to be corrected) these are possible with emacs' current regex engine, and no amount of syntax replacements will fix that.</p>
<p>The solution below addresses the original issues of escaping and additional char classes by replacing with syntax emacs understands. A second answer (now deleted) suggested advising (add a function to run at the start of another) emacs' regex function to do the replacement for all regex processing. The author quickly censored him/herself realizing that it would likely break much existing emacs code, and eventually the post was removed.</p>
<p>I would still like to change the regex-engine to one which supports extensions, but I agree that changing the escaping behavior universally would cause havoc I'm not willing to chase. Thus, I'm changing the subject to match the question and accepting the response.</p>
<p>It crossed my mind to change the engine to support common-syntax and extensions, advise the regex function to convert emacs-internal code to common-syntax, advise the interactive functions to convert my common-syntax to emacs-syntax (so it can be converted back to common)... but I think even RMS would recommend a fork before that.</p>
<p></p> | 879,047 | 2 | 3 | null | 2009-05-18 17:59:59.41 UTC | 6 | 2015-02-09 21:40:02.667 UTC | 2014-01-09 06:33:57.123 UTC | null | 729,907 | null | 80,714 | null | 1 | 43 | regex|emacs|syntax|advising-functions | 4,015 | <p>You could define your own elisp function which modified the regexp and then passed it back to emacs. In pseudo-elisp:</p>
<pre><code>(defun my-query-replace-regexp (regexp)
; modify regexp to replace ( with \(, { with \{, etc.
(query-replace-regexp modified-regexp)
)
; rebind C-% to use new regexp function
(global-set-key "\C-%" 'my-query-replace-regexp)
</code></pre> |
2,639,051 | What is the best way to truncate a date in SQL Server? | <p>If I have a date value like <code>2010-03-01 17:34:12.018</code></p>
<p>What is the most efficient way to turn this into <code>2010-03-01 00:00:00.000</code>?</p>
<p>As a secondary question, what is the best way to emulate Oracle's <code>TRUNC</code> function, which will allow you to truncate at Year, Quarter, Month, Week, Day, Hour, Minute, and Second boundaries?</p> | 2,639,057 | 6 | 1 | null | 2010-04-14 16:12:14.383 UTC | 6 | 2021-11-02 17:27:05.263 UTC | 2014-10-15 16:35:45.98 UTC | null | 57,986 | null | 57,986 | null | 1 | 23 | sql-server|tsql | 74,658 | <p>To round to the nearest <strong>whole day</strong>, there are three approaches in wide use. The first one uses <code>datediff</code> to find the number of days since the <code>0</code> datetime. The <code>0</code> datetime corresponds to the 1st of January, 1900. By adding the day difference to the start date, you've rounded to a whole day;</p>
<pre><code>select dateadd(d, 0, datediff(d, 0, getdate()))
</code></pre>
<p>The second method is text based: it truncates the text description with <code>varchar(10)</code>, leaving only the date part:</p>
<pre><code>select convert(varchar(10),getdate(),111)
</code></pre>
<p>The third method uses the fact that a <code>datetime</code> is really a floating point representing the number of days since 1900. So by rounding it to a whole number, for example using <code>floor</code>, you get the start of the day:</p>
<pre><code>select cast(floor(cast(getdate() as float)) as datetime)
</code></pre>
<p>To answer your second question, the <strong>start of the week</strong> is trickier. One way is to subtract the day-of-the-week:</p>
<pre><code>select dateadd(dd, 1 - datepart(dw, getdate()), getdate())
</code></pre>
<p>This returns a time part too, so you'd have to combine it with one of the time-stripping methods to get to the first date. For example, with <code>@start_of_day</code> as a variable for readability:</p>
<pre><code>declare @start_of_day datetime
set @start_of_day = cast(floor(cast(getdate() as float)) as datetime)
select dateadd(dd, 1 - datepart(dw, @start_of_day), @start_of_day)
</code></pre>
<p>The <strong>start of the year, month, hour and minute</strong> still work with the "difference since 1900" approach:</p>
<pre><code>select dateadd(yy, datediff(yy, 0, getdate()), 0)
select dateadd(m, datediff(m, 0, getdate()), 0)
select dateadd(hh, datediff(hh, 0, getdate()), 0)
select dateadd(mi, datediff(mi, 0, getdate()), 0)
</code></pre>
<p><strong>Rounding by second</strong> requires a different approach, since the number of seconds since <code>0</code> gives an overflow. One way around that is using the start of the day, instead of 1900, as a reference date:</p>
<pre><code>declare @start_of_day datetime
set @start_of_day = cast(floor(cast(getdate() as float)) as datetime)
select dateadd(s, datediff(s, @start_of_day, getdate()), @start_of_day)
</code></pre>
<p>To <strong>round by 5 minutes</strong>, adjust the minute rounding method. Take the quotient of the minute difference, for example using <code>/5*5</code>:</p>
<pre><code>select dateadd(mi, datediff(mi,0,getdate())/5*5, 0)
</code></pre>
<p>This works for quarters and half hours as well.</p> |
3,159,136 | What happens when you hit the SQL Server Express 4GB / 10GB limit? | <p>What kind of error occurs? What do users experience? Can you access the database using tools and what if you get it back under the 4GB / 10GB limit?</p> | 3,159,200 | 7 | 2 | null | 2010-07-01 15:14:31.153 UTC | 3 | 2013-04-17 07:37:13.713 UTC | 2010-07-06 13:35:49.707 UTC | null | 180,430 | null | 180,430 | null | 1 | 24 | sql|database|sql-server-express | 49,223 | <p>As I understand it you will start to see exception messages appear within your event log, such as:</p>
<blockquote>
<p>Could not allocate space for object 'dbo.[table]' in database '[database]' because the
'PRIMARY' filegroup is full. Create disk space by deleting unneeded files,
dropping objects in the filegroup.</p>
</blockquote>
<p>If you can then reduce the size of the database, you can then continue to add etc as before. Tools should carry on working regardless of the database size.</p>
<p>Hope this helps!</p> |
2,839,533 | Adding distance to a GPS coordinate | <p>I'm trying to generate some points at random distances away from a fixed point using GPS.</p>
<p>How can I add distance in meters to a GPS coordinate?
I've looked at UTM to GPS conversion but is there a simpler method to achieve this?</p>
<p>I'm working on Android platform just in case.</p>
<p>Cheers,
fgs</p> | 2,839,560 | 9 | 0 | null | 2010-05-15 08:56:13.317 UTC | 23 | 2021-11-19 21:09:22.69 UTC | 2021-09-20 06:10:48.823 UTC | null | 196,919 | null | 341,842 | null | 1 | 34 | c#|android|gps | 34,318 | <ul>
<li>P0(lat0,lon0) : initial position (unit : <em>degrees</em>) </li>
<li>dx,dy : random offsets from your initial position in <em>meters</em></li>
</ul>
<p>You can use an approximation to compute the position of the randomized position:</p>
<pre><code> lat = lat0 + (180/pi)*(dy/6378137)
lon = lon0 + (180/pi)*(dx/6378137)/cos(lat0)
</code></pre>
<p>This is quite precise as long as the random distance offset is below 10-100 km</p>
<p>Edit: of course in Java Math.cos() expects radians so do use <code>Math.cos(Math.PI/180.0*lat0)</code> if lat0 is in degrees as assumed above.</p> |
2,499,070 | GNU make: should the number of jobs equal the number of CPU cores in a system? | <p>There seems to be some controversy on whether the number of jobs in GNU make is supposed to be equal to the number of cores, or if you can optimize the build time by adding one extra job that can be queued up while the others "work".</p>
<p>Is it better to use <code>-j4</code> or <code>-j5</code> on a quad core system?</p>
<p>Have you seen (or done) any benchmarking that supports one or the other?</p> | 2,499,574 | 10 | 3 | null | 2010-03-23 10:29:10.407 UTC | 29 | 2020-09-09 19:16:36.513 UTC | 2016-07-02 21:35:06.3 UTC | null | 1,128,737 | null | 51,425 | null | 1 | 104 | makefile|gnu-make | 71,581 | <p>I would say the best thing to do is benchmark it yourself on your particular environment and workload. Seems like there are too many variables (size/number of source files, available memory, disk caching, whether your source directory & system headers are located on different disks, etc.) for a one-size-fits-all answer.</p>
<p>My personal experience (on a 2-core MacBook Pro) is that -j2 is significantly faster than -j1, but beyond that (-j3, -j4 etc.) there's no measurable speedup. So for my environment "jobs == number of cores" seems to be a good answer. (YMMV)</p> |
2,632,199 | How do I get the path of the current executed file in Python? | <p>This may seem like a newbie question, but it is not. Some common approaches don't work in all cases:</p>
<h1>sys.argv[0]</h1>
<p>This means using <code>path = os.path.abspath(os.path.dirname(sys.argv[0]))</code>, but this does not work if you are running from another Python script in another directory, and this can happen in real life.</p>
<h1>__file__</h1>
<p>This means using <code>path = os.path.abspath(os.path.dirname(__file__))</code>, but I found that this doesn't work:</p>
<ul>
<li><code>py2exe</code> doesn't have a <code>__file__</code> attribute, but there is <a href="http://www.py2exe.org/index.cgi/WhereAmI" rel="noreferrer">a workaround</a></li>
<li>When you run from <a href="https://en.wikipedia.org/wiki/IDLE" rel="noreferrer">IDLE</a> with <code>execute()</code> there is no <code>__file__</code> attribute</li>
<li><a href="https://en.wikipedia.org/wiki/Mac_OS_X_Snow_Leopard" rel="noreferrer">Mac OS X v10.6</a> (Snow Leopard) where I get <code>NameError: global name '__file__' is not defined</code></li>
</ul>
<p>Related questions with incomplete answers:</p>
<ul>
<li><em><a href="https://stackoverflow.com/questions/1296501/python-find-path-to-file-being-run">Find path to currently running file</a></em></li>
<li><em><a href="https://stackoverflow.com/questions/1483827/python-path-to-current-file-depends-on-how-i-execute-the-program">Path to current file depends on how I execute the program</a></em></li>
<li><em><a href="https://stackoverflow.com/questions/2259503/how-to-know-the-path-of-the-running-script-in-python">How can I know the path of the running script in Python?</a></em></li>
<li><em><a href="https://stackoverflow.com/questions/509742/python-chdir-to-dir-the-py-script-is-in">Change directory to the directory of a Python script</a></em></li>
</ul>
<p>I'm looking for a <strong>generic solution</strong>, one that would work in all above use cases.</p>
<h3>Update</h3>
<p>Here is the result of a testcase:</p>
<h3>Output of <code>python a.py</code> (on Windows)</h3>
<pre><code>a.py: __file__= a.py
a.py: os.getcwd()= C:\zzz
b.py: sys.argv[0]= a.py
b.py: __file__= a.py
b.py: os.getcwd()= C:\zzz
</code></pre>
<h3>a.py</h3>
<pre><code>#! /usr/bin/env python
import os, sys
print "a.py: sys.argv[0]=", sys.argv[0]
print "a.py: __file__=", __file__
print "a.py: os.getcwd()=", os.getcwd()
print
execfile("subdir/b.py")
</code></pre>
<h3>File <em>subdir/b.py</em></h3>
<pre><code>#! /usr/bin/env python
import os, sys
print "b.py: sys.argv[0]=", sys.argv[0]
print "b.py: __file__=", __file__
print "b.py: os.getcwd()=", os.getcwd()
print
</code></pre>
<h3>tree</h3>
<pre><code>C:.
| a.py
\---subdir
b.py
</code></pre> | 2,632,297 | 13 | 0 | null | 2010-04-13 18:37:45.683 UTC | 100 | 2021-09-07 05:53:42.803 UTC | 2021-09-06 19:48:16.137 UTC | null | 63,550 | null | 99,834 | null | 1 | 223 | python|path|directory | 166,811 | <p>You can't directly determine the location of the main script being executed. After all, sometimes the script didn't come from a file at all. For example, it could come from the interactive interpreter or dynamically generated code stored only in memory.</p>
<p>However, you can reliably determine the location of a module, since modules are always loaded from a file. If you create a module with the following code and put it in the same directory as your main script, then the main script can import the module and use that to locate itself.</p>
<p>some_path/module_locator.py:</p>
<pre><code>def we_are_frozen():
# All of the modules are built-in to the interpreter, e.g., by py2exe
return hasattr(sys, "frozen")
def module_path():
encoding = sys.getfilesystemencoding()
if we_are_frozen():
return os.path.dirname(unicode(sys.executable, encoding))
return os.path.dirname(unicode(__file__, encoding))
</code></pre>
<p>some_path/main.py:</p>
<pre><code>import module_locator
my_path = module_locator.module_path()
</code></pre>
<p>If you have several main scripts in different directories, you may need more than one copy of module_locator.</p>
<p>Of course, if your main script is loaded by some other tool that doesn't let you import modules that are co-located with your script, then you're out of luck. In cases like that, the information you're after simply doesn't exist anywhere in your program. Your best bet would be to file a bug with the authors of the tool.</p> |
2,668,854 | Sanitizing strings to make them URL and filename safe? | <p>I am trying to come up with a function that does a good job of sanitizing certain strings so that they are safe to use in the URL (like a post slug) and also safe to use as file names. For example, when someone uploads a file I want to make sure that I remove all dangerous characters from the name.</p>
<p>So far I have come up with the following function which I hope solves this problem and allows foreign UTF-8 data also.</p>
<pre><code>/**
* Convert a string to the file/URL safe "slug" form
*
* @param string $string the string to clean
* @param bool $is_filename TRUE will allow additional filename characters
* @return string
*/
function sanitize($string = '', $is_filename = FALSE)
{
// Replace all weird characters with dashes
$string = preg_replace('/[^\w\-'. ($is_filename ? '~_\.' : ''). ']+/u', '-', $string);
// Only allow one dash separator at a time (and make string lowercase)
return mb_strtolower(preg_replace('/--+/u', '-', $string), 'UTF-8');
}
</code></pre>
<p><strong>Does anyone have any tricky sample data I can run against this - or know of a better way to safeguard our apps from bad names?</strong></p>
<p><em>$is-filename allows some additional characters like temp vim files</em></p>
<p><em>update: removed the star character since I could not think of a valid use</em></p> | 2,695,530 | 23 | 2 | null | 2010-04-19 15:51:44.993 UTC | 75 | 2017-03-12 13:45:48.683 UTC | 2011-06-20 11:45:54.837 UTC | null | 560,648 | null | 99,923 | null | 1 | 141 | php|url|filenames|sanitization | 194,919 | <p>Some observations on your solution:</p>
<ol>
<li>'u' at the end of your pattern means that the <strong>pattern</strong>, and not the text it's matching will be interpreted as UTF-8 (I presume you assumed the latter?). </li>
<li>\w matches the underscore character. You specifically include it for files which leads to the assumption that you don't want them in URLs, but in the code you have URLs will be permitted to include an underscore.</li>
<li>The inclusion of "foreign UTF-8" seems to be locale-dependent. It's not clear whether this is the locale of the server or client. From the PHP docs:</li>
</ol>
<blockquote>
<blockquote>
<p>A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place. For example, in the "fr" (French) locale, some character codes greater than 128 are used for accented letters, and these are matched by \w.</p>
</blockquote>
</blockquote>
<h3>Creating the slug</h3>
<p>You probably shouldn't include accented etc. characters in your post slug since, technically, they should be percent encoded (per URL encoding rules) so you'll have ugly looking URLs.</p>
<p>So, if I were you, after lowercasing, I'd convert any 'special' characters to their equivalent (e.g. é -> e) and replace non [a-z] characters with '-', limiting to runs of a single '-' as you've done. There's an implementation of converting special characters here: <a href="https://web.archive.org/web/20130208144021/http://neo22s.com/slug" rel="noreferrer">https://web.archive.org/web/20130208144021/http://neo22s.com/slug</a></p>
<h3>Sanitization in general</h3>
<p>OWASP have a PHP implementation of their Enterprise Security API which among other things includes methods for safe encoding and decoding input and output in your application. </p>
<p>The Encoder interface provides:</p>
<pre><code>canonicalize (string $input, [bool $strict = true])
decodeFromBase64 (string $input)
decodeFromURL (string $input)
encodeForBase64 (string $input, [bool $wrap = false])
encodeForCSS (string $input)
encodeForHTML (string $input)
encodeForHTMLAttribute (string $input)
encodeForJavaScript (string $input)
encodeForOS (Codec $codec, string $input)
encodeForSQL (Codec $codec, string $input)
encodeForURL (string $input)
encodeForVBScript (string $input)
encodeForXML (string $input)
encodeForXMLAttribute (string $input)
encodeForXPath (string $input)
</code></pre>
<p><a href="https://github.com/OWASP/PHP-ESAPI" rel="noreferrer">https://github.com/OWASP/PHP-ESAPI</a>
<a href="https://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API" rel="noreferrer">https://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API</a></p> |
23,890,806 | How to run a task ONLY on modified file with Gulp watch | <p>I have the current gulp task which I use in a gulpfile. Path are from a config.json and everything works perfectly:</p>
<pre class="lang-js prettyprint-override"><code>//Some more code and vars...
gulp.task('watch', function() {
gulp.watch([config.path.devfolder+"/**/*.png", config.path.devfolder+"/**/*.jpg", config.path.devfolder+"/**/*.gif", config.path.devfolder+"/**/*.jpeg"], ['imagemin-cfg']);
})
//Some more code ...
gulp.task('imagemin-cfg', function () {
return gulp.src([config.path.devfolder+"/**/*.png", config.path.devfolder+"/**/*.jpg", config.path.devfolder+"/**/*.gif", config.path.devfolder+"/**/*.jpeg"], {read: false})
.pipe(imagemin({
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngcrush()]
}))
.pipe(gulp.dest(buildType))
.pipe(connect.reload());
});
</code></pre>
<p>But I still have an issue, the number of images in my project is huge and this task takes ages. I'm looking for a way to run my task ONLY on modified files. If I had an image or modify it, <code>imagemin()</code> will only run on this image, and not on all.</p>
<p>Once again everything is working perfectly fine, but the run time is really long.</p>
<p>Thanks.</p> | 24,010,523 | 9 | 0 | null | 2014-05-27 13:31:14.217 UTC | 8 | 2022-02-18 17:41:43.603 UTC | 2014-09-23 00:31:20.463 UTC | null | 64,046 | null | 3,641,315 | null | 1 | 60 | gulp|gulp-watch | 42,636 | <p>"gulp-changed" is not a best solution for doing this, because it watch only modified filed in "buildType" folder.</p>
<p>Try <a href="https://github.com/wearefractal/gulp-cached" rel="noreferrer">gulp-cached</a> instead.</p> |
23,800,477 | Java 8 Time API: how to parse string of format "MM.yyyy" to LocalDate | <p>I'm a bit discouraged with parsing dates in <em>Java 8 Time API</em>.</p>
<p>Previously I could easily write:</p>
<pre><code>String date = "04.2013";
DateFormat df = new SimpleDateFormat("MM.yyyy");
Date d = df.parse(date);
</code></pre>
<p>But now if I use <em>LocalDate</em> and do it like this:</p>
<pre><code>String date = "04.2013";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM.yyyy");
LocalDate ld = LocalDate.parse(date, formatter);
</code></pre>
<p>I receive an exception:</p>
<pre><code>java.time.format.DateTimeParseException: Text '04' could not be parsed at index 0
java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1948)
java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1850)
java.time.LocalDate.parse(LocalDate.java:400)
java.time.LocalDate.parse(LocalDate.java:385)
com.luxoft.ath.controllers.JsonController.region(JsonController.java:38)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:483)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
</code></pre>
<p>If I change string format to <em>"yyyy-MM-dd"</em> everything work perfectly, even without formatter: </p>
<pre><code>String date = "2013-04-12";
LocalDate ld = LocalDate.parse(date);
</code></pre>
<p>So my question is: how to parse date in custom format using Java 8 Time API?</p> | 23,800,649 | 2 | 0 | null | 2014-05-22 07:33:08.377 UTC | 6 | 2014-05-26 07:48:28.907 UTC | null | null | null | null | 1,430,055 | null | 1 | 50 | java|date|java-8|java-time | 27,112 | <p>It makes sense: your input is not really a date because it does not have a day information. You should parse it as a <code>YearMonth</code> and use that result if you don't care about the day.</p>
<pre><code>String date = "04.2013";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM.yyyy");
YearMonth ym = YearMonth.parse(date, formatter);
</code></pre>
<p>If you do need to apply a specific day, you can obtain a <code>LocalDate</code> from a <code>YearMonth</code> for example:</p>
<pre><code>LocalDate ld = ym.atDay(1);
//or
LocalDate ld = ym.atEndOfMonth();
</code></pre>
<p>You can also use a <code>TemporalAdjuster</code>, for example, for the last day of the month*:</p>
<pre><code>LocalDate ld = ym.atDay(1).with(lastDayOfMonth());
</code></pre>
<p><sub> *with an <code>import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;</code></sub></p> |
10,503,909 | How can I launch a URL in the users default browser from my application? | <p>How can I have a button in my desktop application that causes the user's default browser to launch and display a URL supplied by the application's logic.</p> | 10,503,920 | 2 | 0 | null | 2012-05-08 17:59:13.627 UTC | 4 | 2016-11-29 14:16:44.643 UTC | null | null | null | null | 398,546 | null | 1 | 37 | c#|browser|desktop-application | 48,856 | <pre><code> Process.Start("http://www.google.com");
</code></pre> |
10,402,777 | Share session (cookies) between subdomains in Rails? | <p>I have an app setup where each user belongs to a company, and that company has a subdomain (I am using basecamp style subdomains). The problem that I am facing is that rails is creating multiple cookies (one for lvh.me and another for subdomain.lvh.me) which is causing quite a few breaks in my application(such as flash messages being persistent though out all requests once signed in).</p>
<p>I have this in my /cofig/initilizers/session_store.rb file:</p>
<pre><code>AppName::Application.config.session_store :cookie_store, key: '_application_devise_session', domain: :all
</code></pre>
<p>The domain: :all seems to be the standard answer I found on Google, but that doesn't seem to be working for me. Any help is appreciated! </p> | 10,403,338 | 9 | 0 | null | 2012-05-01 19:02:40.17 UTC | 37 | 2020-06-25 04:39:32.51 UTC | 2012-05-01 19:11:17.127 UTC | user166390 | null | null | 949,953 | null | 1 | 97 | ruby-on-rails|session|devise | 52,199 | <p>As it turns outs 'domain: all' creates a cookie for all the different subdomains that are visited during that session (and it ensures that they are passed around between request). If no domain argument is passed, it means that a new cookie is created for every different domain that is visited in the same session and the old one gets discarded. What I needed was a single cookie that is persistent throughout the session, even when the domain changes. Hence, passing <code>domain: "lvh.me"</code> solved the problem in development. This creates a single cookie that stays there between different subdomains.</p>
<p>For anyone needing further explanation, this is a great link:
<a href="http://excid3.com/blog/sharing-a-devise-user-session-across-subdomains-with-rails-3/" rel="noreferrer">http://excid3.com/blog/sharing-a-devise-user-session-across-subdomains-with-rails-3/</a></p> |
6,029,495 | How can I generate random number in specific range in Android? | <p>I want to generate random number in a specific range. (Ex. Range Between 65 to 80)</p>
<p>I try as per below code, but it is not very use full. It also returns the value greater then max. value(greater then 80).</p>
<pre><code>Random r = new Random();
int i1 = (r.nextInt(80) + 65);
</code></pre>
<p>How can I generate random number between a range?</p> | 6,029,519 | 2 | 1 | null | 2011-05-17 10:27:55.487 UTC | 51 | 2021-08-26 11:16:09.31 UTC | 2021-08-26 11:16:09.31 UTC | null | 8,583,692 | null | 544,512 | null | 1 | 281 | java|android|kotlin|random | 479,386 | <pre><code>Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;
</code></pre>
<p>This gives a random integer between 65 (inclusive) and 80 (exclusive), one of <code>65,66,...,78,79</code>.</p> |
19,598,088 | should Class.getResourceAsStream be closed? | <p>I was wondering if this is required since when I use this method, the file is being read from the classpath. Does "not closing" it lead to a memory leak.</p>
<p>How can I test for such memory leaks?</p> | 19,598,166 | 3 | 0 | null | 2013-10-25 19:36:18.863 UTC | 2 | 2021-09-01 13:29:32.523 UTC | 2021-02-13 11:42:23.45 UTC | null | 466,862 | null | 634,910 | null | 1 | 45 | java | 16,535 | <p>You are assuming that <code>Class.getResourceAsStream()</code> will always return a stream that points to a file inside your class' JAR file. This is incorrect. Your classpath may also contains folders, in which case <code>Class.getResourceAsStream()</code> will return a <code>FileInputStream</code>. Some other class loaders might also return other type of resources, such as remote files (in the case of a URLClassLoader).</p>
<p>Even in the case of a JAR file, it is possible that the implementation maintain, by whatever mean, a persistant view inside the JAR file to the compressed bytes of the file you are accessing. Maybe it is holding upon a memory mapped <code>ByteBuffer</code>...</p>
<p>Why take the chance? You should always close streams (and any other Closeable, actually), no matter how they were given to you.</p>
<p>Note that since Java 7, the preferred method to handle closing <em>any</em> resource is definitely the try-with-resources construct. It correctly handles several corner cases that are very hard to manage in hand written code, and yet it is almost as easy to write for you as if you had simply forgot about closing the resource. For example, you may use code like this:</p>
<pre><code> try (InputStream in = Class.getResourceAsStream("someresource.txt")) {
// Use the stream as you need to...
}
// Then forget about it... and yet, it has been closed properly.
</code></pre>
<p>As for detecting leaks, the best strategy is to obtain a memory dump at the time the VM is shut down, then analyze it with some tool. Two popular tools are <a href="https://visualvm.github.io/" rel="nofollow noreferrer">VisualVM</a> and <a href="https://www.eclipse.org/mat/" rel="nofollow noreferrer">Eclipse mat</a>.</p> |
19,319,116 | .Include() vs .Load() performance in EntityFramework | <p>When querying a large table where you need to access the navigation properties later on in code (I explicitly don't want to use lazy loading) what will perform better <code>.Include()</code> or <code>.Load()</code>? Or why use the one over the other?</p>
<p>In this example the included tables all only have about 10 entries and employees has about 200 entries, and it can happen that most of those will be loaded anyway with include because they match the where clause.</p>
<pre><code>Context.Measurements.Include(m => m.Product)
.Include(m => m.ProductVersion)
.Include(m => m.Line)
.Include(m => m.MeasureEmployee)
.Include(m => m.MeasurementType)
.Where(m => m.MeasurementTime >= DateTime.Now.AddDays(-1))
.ToList();
</code></pre>
<p>or</p>
<pre><code>Context.Products.Load();
Context.ProductVersions.Load();
Context.Lines.Load();
Context.Employees.Load();
Context.MeasurementType.Load();
Context.Measurements.Where(m => m.MeasurementTime >= DateTime.Now.AddDays(-1))
.ToList();
</code></pre> | 19,319,663 | 6 | 0 | null | 2013-10-11 13:14:58.367 UTC | 25 | 2019-03-06 17:05:22.253 UTC | null | null | null | null | 503,059 | null | 1 | 71 | c#|.net|entity-framework | 53,193 | <h2>It depends, try both</h2>
<p>When using <code>Include()</code>, you get the <strong>benefit</strong> of loading all of your data in a single call to the underlying data store. If this is a remote SQL Server, for example, that can be a major performance boost.</p>
<p>The <strong>downside</strong> is that <code>Include()</code> queries tend to get <em>really</em> <strong>complicated</strong>, especially if you have any filters (<code>Where()</code> calls, for example) or try to do any grouping. EF will generate very heavily nested queries using sub-<code>SELECT</code> and <code>APPLY</code> statements to get the data you want. It is also much less efficient -- you get back a single row of data with every possible child-object column in it, so data for your top level objects will be repeated a lot of times. (For example, a single parent object with 10 children will product 10 rows, each with the same data for the parent-object's columns.) I've had single <strong>EF queries get so complex they caused deadlocks</strong> when running at the same time as EF update logic.</p>
<p>The <code>Load()</code> method is much <strong>simpler</strong>. Each query is a single, easy, straightforward <code>SELECT</code> statement against a single table. These are much easier in every possible way, <em>except</em> you have to do many of them (possibly many times more). If you have nested collections of collections, you may even need to loop through your top level objects and <code>Load</code> their sub-objects. It can get out of hand.</p>
<h2>Quick rule-of-thumb</h2>
<p>Try to <strong>avoid</strong> having any <strong>more than three <code>Include</code> calls</strong> in a single query. I find that EF's queries get too ugly to recognize beyond that; it also matches my rule-of-thumb for SQL Server queries, that up to four JOIN statements in a single query works very well, but after that it's time to <em>consider refactoring</em>.</p>
<p>However, all of that is only a starting point. </p>
<p><strong>It depends on your schema, your environment, your data</strong>, and many other factors. </p>
<p>In the end, you will just need to <strong>try it out each way</strong>. </p>
<p><em>Pick a reasonable "default" pattern to use, see if it's good enough, and if not, optimize to taste.</em></p> |
34,078,676 | Access-Control-Allow-Origin: "*" not allowed when credentials flag is true, but there is no Access-Control-Allow-Credentials header | <p>Suddenly, seemingly without changing anything in my web app, I started getting CORS errors when opening it in Chrome. I tried adding an <code>Access-Control-Allow-Origin: *</code> header. Then I get this error:</p>
<p><code>
XMLHttpRequest cannot load http://localhost:9091/sockjs-node/info?t= 1449187563637. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:3010' is therefore not allowed access.
</code></p>
<p>But as you can see in the following image, there is no <code>Access-Control-Allow-Credentials</code> header.</p>
<p><a href="https://i.stack.imgur.com/qchoG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qchoG.png" alt="enter image description here"></a></p>
<p>WTF? Chrome bug?</p>
<p>My page is loaded at <code>http://localhost:3010</code> and that server also uses <code>Access-Control-Allow-Origin: *</code> without problems. Is there a problem if the two endpoints both use it?</p> | 34,099,399 | 3 | 0 | null | 2015-12-04 00:08:10.887 UTC | 4 | 2017-10-15 14:00:04.343 UTC | 2015-12-04 23:51:10.893 UTC | null | 200,224 | null | 200,224 | null | 1 | 20 | xmlhttprequest|cors|same-origin-policy | 75,980 | <p><strong>"credentials flag" refers to <code>XMLHttpRequest.withCredentials</code> of the request being made, not to an <code>Access-Control-Allow-Credentials</code> header.</strong> That was the source of my confusion.</p>
<p>If the request's <code>withCredentials</code> is <code>true</code>, <code>Access-Control-Allow-Origin: *</code> can't be used, even if there is no <code>Access-Control-Allow-Credentials</code> header.</p> |
52,083,380 | In Docker image names what is the difference between Alpine, Jessie, Stretch, and Buster? | <p>I am just looking at docker images in <a href="https://hub.docker.com/_/node/" rel="noreferrer">https://hub.docker.com/_/node/</a></p>
<p>For every version, the images are categorized into Alpine, Jessie, Stretch, Buster etc. What's their meaning?</p> | 52,083,713 | 2 | 0 | null | 2018-08-29 17:44:12.42 UTC | 31 | 2022-02-09 07:27:47.403 UTC | 2020-02-06 08:13:17.1 UTC | null | 1,374,086 | null | 515,774 | null | 1 | 99 | docker|alpine-linux|docker-image|debian-jessie|debian-buster | 39,880 | <p>Those are the names of the OS in the container in which Node will be running.</p>
<p>Alpine is for Alpine Linux, Jessie and Stretch are versions of Debian. If you scroll down on the documentation link you provided, you'll find a section describing what Alpine is and why you might want to use it.</p> |
20,909,446 | Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger | <p>I've got an interesting problem in which the org.apache.log4j.Logger class is not found during runtime. I'm trying to get authorized and that is where it's failing:</p>
<p><code>OAuthAuthorizer oauthAuthorizer = new OAuthAuthorizer(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, SAML_PROVIDER_ID, userId);</code></p>
<p>I'm using JDeveloper 11.1.1.6. Here is what I know:</p>
<ol>
<li><p>I've looked in my UI.war/WEB-INF/lib directory and I see the log4j-1.2.17.jar there.</p></li>
<li><p>The class complaining about it is org.opensaml.xml.XMLConfigurator</p>
<pre><code>Caused by: java.lang.NoClassDefFoundError: org/apache/log4j/Logger
at org.opensaml.xml.XMLConfigurator.<clinit>(XMLConfigurator.java:60)
at org.opensaml.DefaultBootstrap.initializeXMLTooling(DefaultBootstrap.java:195)
at org.opensaml.DefaultBootstrap.bootstrap(DefaultBootstrap.java:91)
at com.intuit.ipp.aggcat.util.SAML2AssertionGenerator.getSAMLBuilder(SAML2AssertionGenerator.java:156)
at com.intuit.ipp.aggcat.util.SAML2AssertionGenerator.createSubject(SAML2AssertionGenerator.java:187)
at com.intuit.ipp.aggcat.util.SAML2AssertionGenerator.buildAssertion(SAML2AssertionGenerator.java:114)
at com.intuit.ipp.aggcat.util.SAML2AssertionGenerator.generateSignedAssertion(SAML2AssertionGenerator.java:83)
at com.intuit.ipp.aggcat.util.SamlUtil.createSignedSAMLPayload(SamlUtil.java:156)
at com.intuit.ipp.aggcat.util.OAuthUtil.getOAuthTokens(OAuthUtil.java:60)
at com.intuit.ipp.aggcat.core.OAuthAuthorizer.<init>(OAuthAuthorizer.java:85)
at com.incomemax.view.intuit.WebUtil.getAggCatService(WebUtil.java:91)
</code></pre>
<pre><code>Caused by: java.lang.ClassNotFoundException: org.apache.log4j.Logger
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:305)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:246)
... 64 more
</code></pre></li>
<li><p>I decomplied XMLConfigurator and oddly it doesn't import org.apache.log4j.Logger It uses org.slf4j.Logger which is also in my jars directory (slf4j-api-1.7.5.jar). Also interesting is that line 60 (see stack trace) is a blank line in my decompile.</p></li>
<li><p>Of course if I add Logger.xxxxx during design time, it finds it just fine.</p></li>
<li><p>I'm using the code/jars directly from the sample java code, but imported into my existing application.</p></li>
</ol>
<p>I've been scouring the web for answers and I believe I've checked all the areas I can think of. I also referenced this very good page: <a href="http://myarch.com/classnotfound/" rel="noreferrer">http://myarch.com/classnotfound/</a></p>
<p>Given authorization is step 1 in using the Intuit Developer API, I'm kinda stuck.</p>
<p>Adding output from @jhadesdev suggestion:</p>
<p>All versions of log4j Logger: </p>
<ul>
<li>zip:C:/Users/Chris/AppData/Roaming/JDeveloper/system11.1.1.6.38.61.92/DefaultDomain/servers/DefaultServer/tmp/_WL_user/j2ee-app/lt5l71/war/WEB-INF/lib/log4j-1.2.17.jar!/org/apache/log4j/Logger.class</li>
</ul>
<p>All versions of log4j visible from the classloader of the OAuthAuthorizer class: </p>
<ul>
<li>zip:C:/Users/Chris/AppData/Roaming/JDeveloper/system11.1.1.6.38.61.92/DefaultDomain/servers/DefaultServer/tmp/_WL_user/j2ee-app/lt5l71/war/WEB-INF/lib/log4j-1.2.17.jar!/org/apache/log4j/Logger.class</li>
</ul>
<p>All versions of XMLConfigurator: </p>
<ul>
<li><p>jar:file:/C:/Oracle/Middleware11116/modules/com.bea.core.bea.opensaml2_1.0.0.0_6-1-0-0.jar!/org/opensaml/xml/XMLConfigurator.class</p></li>
<li><p>zip:C:/Users/Chris/AppData/Roaming/JDeveloper/system11.1.1.6.38.61.92/DefaultDomain/servers/DefaultServer/tmp/_WL_user/j2ee-app/lt5l71/war/WEB-INF/lib/ipp-java-aggcat-v1-devkit-1.0.2.jar!/org/opensaml/xml/XMLConfigurator.class</p></li>
<li><p>zip:C:/Users/Chris/AppData/Roaming/JDeveloper/system11.1.1.6.38.61.92/DefaultDomain/servers/DefaultServer/tmp/_WL_user/j2ee-app/lt5l71/war/WEB-INF/lib/xmltooling-1.3.1.jar!/org/opensaml/xml/XMLConfigurator.class</p></li>
</ul>
<p>All versions of XMLConfigurator visible from the class loader of the OAuthAuthorizer class:</p>
<ul>
<li><p>jar:file:/C:/Oracle/Middleware11116/modules/com.bea.core.bea.opensaml2_1.0.0.0_6-1-0-0.jar!/org/opensaml/xml/XMLConfigurator.class</p></li>
<li><p>zip:C:/Users/Chris/AppData/Roaming/JDeveloper/system11.1.1.6.38.61.92/DefaultDomain/servers/DefaultServer/tmp/_WL_user/j2ee-app/lt5l71/war/WEB-INF/lib/ipp-java-aggcat-v1-devkit-1.0.2.jar!/org/opensaml/xml/XMLConfigurator.class</p></li>
<li><p>zip:C:/Users/Chris/AppData/Roaming/JDeveloper/system11.1.1.6.38.61.92/DefaultDomain/servers/DefaultServer/tmp/_WL_user/j2ee-app/lt5l71/war/WEB-INF/lib/xmltooling-1.3.1.jar!/org/opensaml/xml/XMLConfigurator.class</p></li>
</ul>
<p>I'm still working on interpreting the results.</p> | 20,913,280 | 10 | 1 | null | 2014-01-03 17:34:40.263 UTC | 9 | 2022-03-24 20:00:52.393 UTC | 2014-01-03 22:05:39.097 UTC | null | 1,549,818 | null | 3,083,573 | null | 1 | 67 | java|logging|classpath|classloader|intuit-partner-platform | 314,929 | <p>With the suggestions @jhadesdev and the explanations from others, I've found the issue here.</p>
<p>After adding the code to see what was visible to the various class loaders I found this:</p>
<pre><code>All versions of log4j Logger:
zip:<snip>war/WEB-INF/lib/log4j-1.2.17.jar!/org/apache/log4j/Logger.class
All versions of log4j visible from the classloader of the OAuthAuthorizer class:
zip:<snip>war/WEB-INF/lib/log4j-1.2.17.jar!/org/apache/log4j/Logger.class
All versions of XMLConfigurator:
jar:<snip>com.bea.core.bea.opensaml2_1.0.0.0_6-1-0-0.jar!/org/opensaml/xml/XMLConfigurator.class
zip:<snip>war/WEB-INF/lib/ipp-java-aggcat-v1-devkit-1.0.2.jar!/org/opensaml/xml/XMLConfigurator.class
zip:<snip>war/WEB-INF/lib/xmltooling-1.3.1.jar!/org/opensaml/xml/XMLConfigurator.class
All versions of XMLConfigurator visible from the classloader of the OAuthAuthorizer class:
jar:<snip>com.bea.core.bea.opensaml2_1.0.0.0_6-1-0-0.jar!/org/opensaml/xml/XMLConfigurator.class
zip:<snip>war/WEB-INF/lib/ipp-java-aggcat-v1-devkit-1.0.2.jar!/org/opensaml/xml/XMLConfigurator.class
zip:<snip>war/WEB-INF/lib/xmltooling-1.3.1.jar!/org/opensaml/xml/XMLConfigurator.class
</code></pre>
<p>I noticed that another version of XMLConfigurator was possibly getting picked up.
I decompiled that class and found this at line 60 (where the error was in the original stack trace) <code>private static final Logger log = Logger.getLogger(XMLConfigurator.class);</code> and that class was importing from <code>org.apache.log4j.Logger</code>!</p>
<p>So it was this class that was being loaded and used. My fix was to rename the jar file that contained this file as I can't find where I explicitly or indirectly load it. Which may pose a problem when I actually deploy.</p>
<p>Thanks for all help and the much needed lesson on class loading.</p> |
21,295,936 | Can dplyr summarise over several variables without listing each one? | <p>dplyr is amazingly fast, but I wonder if I'm missing something: is it possible summarise over several variables. For example: </p>
<pre><code>library(dplyr)
library(reshape2)
(df=dput(structure(list(sex = structure(c(1L, 1L, 2L, 2L), .Label = c("boy",
"girl"), class = "factor"), age = c(52L, 58L, 40L, 62L), bmi = c(25L,
23L, 30L, 26L), chol = c(187L, 220L, 190L, 204L)), .Names = c("sex",
"age", "bmi", "chol"), row.names = c(NA, -4L), class = "data.frame")))
sex age bmi chol
1 boy 52 25 187
2 boy 58 23 220
3 girl 40 30 190
4 girl 62 26 204
dg=group_by(df,sex)
</code></pre>
<p>With this small dataframe, it's easy to write</p>
<pre><code>summarise(dg,mean(age),mean(bmi),mean(chol))
</code></pre>
<p>And I know that to get what I want, I could melt, get the means, and then dcast such as </p>
<pre><code>dm=melt(df, id.var='sex')
dmg=group_by(dm, sex, variable);
x=summarise(dmg, means=mean(value))
dcast(x, sex~variable)
</code></pre>
<p>But what if I have >20 variables and a very large number of rows. Is there anything similar to .SD in data.table that would allow me to take the means of all variables in the grouped data frame? Or, is it possible to somehow use lapply on the grouped data frame?</p>
<p>Thanks for any help</p> | 21,296,364 | 2 | 1 | null | 2014-01-22 23:04:11.767 UTC | 37 | 2021-08-20 20:59:18.943 UTC | 2018-06-12 11:55:23.747 UTC | null | 6,323,610 | null | 535,917 | null | 1 | 78 | r|dplyr | 41,463 | <p>The <code>data.table</code> idiom is <code>lapply(.SD, mean)</code>, which is </p>
<pre><code>DT <- data.table(df)
DT[, lapply(.SD, mean), by = sex]
# sex age bmi chol
# 1: boy 55 24 203.5
# 2: girl 51 28 197.0
</code></pre>
<p>I'm not sure of a <code>dplyr</code> idiom for the same thing, but you can do something like</p>
<pre><code>dg <- group_by(df, sex)
# the names of the columns you want to summarize
cols <- names(dg)[-1]
# the dots component of your call to summarise
dots <- sapply(cols ,function(x) substitute(mean(x), list(x=as.name(x))))
do.call(summarise, c(list(.data=dg), dots))
# Source: local data frame [2 x 4]
# sex age bmi chol
# 1 boy 55 24 203.5
# 2 girl 51 28 197.0
</code></pre>
<p>Note that there is a github issue <a href="https://github.com/hadley/dplyr/issues/178" rel="noreferrer">#178</a> to efficienctly implement the <code>plyr</code> idiom <code>colwise</code> in <code>dplyr</code>.</p> |
19,202,093 | How to select columns from groupby object in pandas? | <p>I grouped my dataframe by the two columns below</p>
<pre><code>df = pd.DataFrame({'a': [1, 1, 3],
'b': [4.0, 5.5, 6.0],
'c': [7L, 8L, 9L],
'name': ['hello', 'hello', 'foo']})
df.groupby(['a', 'name']).median()
</code></pre>
<p>and the result is:</p>
<pre><code> b c
a name
1 hello 4.75 7.5
3 foo 6.00 9.0
</code></pre>
<p>How can I access the <code>name</code> field of the resulting median (in this case <code>hello, foo</code>)? This fails:</p>
<pre><code>df.groupby(['a', 'name']).median().name
</code></pre> | 19,202,149 | 4 | 0 | null | 2013-10-05 19:58:29.533 UTC | 8 | 2020-03-05 21:14:22.95 UTC | 2017-09-12 05:14:25.54 UTC | null | 2,137,255 | user248237 | null | null | 1 | 30 | python|pandas | 78,534 | <p>You need to get the index values, they are not columns. In this case level 1</p>
<pre><code>df.groupby(["a", "name"]).median().index.get_level_values(1)
Out[2]:
Index([u'hello', u'foo'], dtype=object)
</code></pre>
<p>You can also pass the index name</p>
<pre><code>df.groupby(["a", "name"]).median().index.get_level_values('name')
</code></pre>
<p>as this will be more intuitive than passing integer values.</p>
<p>You can convert the index values to a list by calling <code>tolist()</code></p>
<pre><code>df.groupby(["a", "name"]).median().index.get_level_values(1).tolist()
Out[5]:
['hello', 'foo']
</code></pre> |
51,958,950 | Error message. "Props with type Object/Array must use a factory function to return the default value." | <p>I am using Vue-Cli3.0. I used this module for Vue.js. <a href="https://github.com/holiber/sl-vue-tree" rel="noreferrer">https://github.com/holiber/sl-vue-tree</a></p>
<p>This is a customizable draggable tree component for Vue.js but I found that it could not copy functions of object.</p>
<p><a href="https://github.com/holiber/sl-vue-tree/blob/master/src/sl-vue-tree.js#L715" rel="noreferrer">https://github.com/holiber/sl-vue-tree/blob/master/src/sl-vue-tree.js#L715</a></p>
<p>Because of here.</p>
<pre><code>JSON.parse(JSON.stringify(entity))
</code></pre>
<p>So I used this module and edited the copy function.</p>
<p><a href="https://www.npmjs.com/package/clone" rel="noreferrer">https://www.npmjs.com/package/clone</a></p>
<pre><code>var clone = require('clone');
copy(entity) {
return clone(entity)
},
</code></pre>
<p>In this way, the function of the object is correctly copied.</p>
<p>I already have tested it, and it worked correctly. There was no problem with the performance but I got a console error.</p>
<pre><code>[Vue warn]: Invalid default value for prop "multiselectKey": Props with type Object/Array must use a factory function to return the default value.
found in
---> <SlVueTree>
</code></pre>
<p>I want to know the way to erase this error.
Thank you for reading my question.</p> | 51,959,056 | 4 | 0 | null | 2018-08-22 02:05:09.8 UTC | 7 | 2022-03-05 08:57:02.82 UTC | 2019-02-05 20:32:49.83 UTC | null | 304,151 | null | 10,257,395 | null | 1 | 57 | javascript|typescript|vue.js|vuejs2 | 55,993 | <p>according to your console warn, i find the error </p>
<p><a href="https://github.com/holiber/sl-vue-tree/blob/master/src/sl-vue-tree.js#L30" rel="noreferrer">https://github.com/holiber/sl-vue-tree/blob/master/src/sl-vue-tree.js#L30</a></p>
<p>try to fix it like this:</p>
<pre><code>multiselectKey: {
type: [String, Array],
default: function () {
return ['ctrlKey', 'metaKey']
},
validator: function (value) {
let allowedKeys = ['ctrlKey', 'metaKey', 'altKey'];
let multiselectKeys = Array.isArray(value) ? value : [value];
multiselectKeys = multiselectKeys.filter(keyName => allowedKeys.indexOf(keyName ) !== -1);
return !!multiselectKeys.length;
}
},
</code></pre>
<p>the component default value must use a factory function to return!</p>
<p>try it and hope it can help you</p> |
9,007,051 | rs.last() gives Invalid operation for forward only resultset : last | <p>I am trying to get the row count of a result set by:</p>
<pre><code>rs.last();
int row_count = rs.getRow();
</code></pre>
<p>but im getting an <code>Invalid operation for forward only resultset : last</code> error. The result set is getting its data from an Oracle 10g database.</p>
<p>Here is how i set up my connection:</p>
<pre><code> Class.forName("oracle.jdbc.driver.OracleDriver");
String connectionString = "jdbc:oracle:thin:@" + oracle_ip_address + ":" + oracle_db_port + ":" + oracle_db_sid;
Connection conn = DriverManager.getConnection(connectionString, oracle_db_username, oracle_db_password);
</code></pre> | 9,007,214 | 2 | 0 | null | 2012-01-25 17:19:23.533 UTC | 3 | 2018-03-08 06:27:38.377 UTC | 2014-04-24 14:06:52.843 UTC | null | 2,273,758 | null | 802,331 | null | 1 | 21 | java|oracle|jdbc|resultset | 56,944 | <p><code>ResultSet.last()</code> and other "absolutely-indexed" query operations are only available when the result set is <em>scrollable</em>; otherwise, you can only iterate one-by-one through the <em>forward-only</em> result set.</p>
<p>The following example (from <a href="https://docs.oracle.com/javase/8/docs/api/java/sql/ResultSet.html" rel="noreferrer">the javadocs</a>) demonstrates how to create a scrollable <code>ResultSet</code>. </p>
<pre><code>Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY
);
ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2");
</code></pre>
<p>Keep in mind that there are performance implications to using scrollable queries. If the goal of this particular <code>ResultSet</code> is only to grab its last value, please consider refining your query to return only that result.</p> |
8,898,182 | How to handle key press event in console application | <p>I want to create a console application that will display the key that is pressed on the console screen, I made this code so far:</p>
<pre><code> static void Main(string[] args)
{
// this is absolutely wrong, but I hope you get what I mean
PreviewKeyDownEventArgs += new PreviewKeyDownEventArgs(keylogger);
}
private void keylogger(KeyEventArgs e)
{
Console.Write(e.KeyCode);
}
</code></pre>
<p>I want to know, what should I type in main so I can call that event?</p> | 8,898,251 | 3 | 0 | null | 2012-01-17 16:29:35.577 UTC | 8 | 2022-04-27 06:48:29.93 UTC | 2016-09-16 13:42:21.797 UTC | null | 3,313,383 | null | 1,079,392 | null | 1 | 29 | c#|event-handling|keyboard-events|keylogger | 78,697 | <p>For console application you can do this, the <code>do while</code> loop runs untill you press <code>x</code></p>
<pre><code>public class Program
{
public static void Main()
{
ConsoleKeyInfo keyinfo;
do
{
keyinfo = Console.ReadKey();
Console.WriteLine(keyinfo.Key + " was pressed");
}
while (keyinfo.Key != ConsoleKey.X);
}
}
</code></pre>
<p>This will only work if your <strong>console application has focus</strong>. If you want to gather system wide key press events you can use <a href="http://www.codeproject.com/KB/cs/globalhook.aspx" rel="noreferrer">windows hooks</a></p> |
8,977,649 | How to locate the vimrc file used by Vim? | <p>Is there a command in the Vim editor to find the <code>.vimrc</code> file location?</p> | 8,977,682 | 3 | 0 | null | 2012-01-23 19:46:09.97 UTC | 41 | 2022-06-18 21:08:54.363 UTC | 2022-06-18 21:08:54.363 UTC | null | 775,954 | null | 265,130 | null | 1 | 170 | vim|command|configuration-files | 118,126 | <p>Just try doing the following:</p>
<pre><code>:version
</code></pre>
<p>You will get an output which includes something like:</p>
<pre><code> system vimrc file: "$VIM/vimrc"
user vimrc file: "$HOME/.vimrc"
user exrc file: "$HOME/.exrc"
system gvimrc file: "$VIM/gvimrc"
user gvimrc file: "$HOME/.gvimrc"
system menu file: "$VIMRUNTIME/menu.vim"
</code></pre>
<p>As noted by Herbert in comments, this is where <code>vim</code> <em>looks for</em> <code>vimrc</code>s, it doesn't mean they exist.</p>
<p>You can check the full path of your <code>vimrc</code> with</p>
<pre><code>:echo $MYVIMRC
</code></pre>
<p>If the output is empty, then your <code>vim</code> doesn't use a user <code>vimrc</code> (just create it if you wish).</p> |
26,898,314 | Icon on left of Bootstrap alert | <p>I'm trying to put a glyphicon on the left side of an alert div. When the alert's text is more than one line, I want the new line to start where the first line's text started, rather than under the glyphicon.</p>
<p>If I use divs for the icon and message, the icon sits on top of the message. If I use spans, the message follows the icon and wraps under it.</p>
<p>Assume the glyphicon's width is not known ahead of time, so using the <code>::first-line</code> selector isn't viable without something more clever than I. I also don't want to put the glyphicon in a <code>.col-*</code> because <code>.col-*-1</code> is way too large. <code>.pull-left</code> and <code>.pull-right</code> haven't seemed to have an effect, regardless of whether I use a div or a span for the glyphicon and message.</p>
<p>The easiest solution is to use a table (le gasp!), but I'm trying to avoid that.</p>
<p>I'm also still deciding whether I want the icon to be at the top left or middle left of the alert. Even with a table, I was having trouble centering the icon vertically.</p>
<p>What I have (pretty simple):</p>
<pre><code><div class="col-sm-9 col-md-10">
<div class="col-xs-12 alert alert-warning">
<div class="glyphicon glyphicon-exclamation-sign"></div>
<div>My message here. Lots of text for several lines! My message here. Lots of text for several lines! My message here. Lots of text for several lines! My message here. Lots of text for several lines!</div>
</div>
<div>
</code></pre>
<p>Link to <a href="http://jsfiddle.net/0vzmmn0v/" rel="noreferrer">JSFiddle</a></p>
<p>Any ideas?</p> | 49,906,980 | 5 | 0 | null | 2014-11-12 23:00:33.3 UTC | 2 | 2020-11-22 18:21:05.84 UTC | null | null | null | null | 3,120,446 | null | 1 | 17 | css|html|twitter-bootstrap-3 | 46,724 | <p>There is now a cleaner (and better best practices imo) way to do this. (Updated <a href="http://jsfiddle.net/0vzmmn0v/271/" rel="nofollow noreferrer">jsfiddle</a> from OP)</p>
<pre><code>.alert {
display: flex;
flex-direction: row;
}
.alert .glyphicon {
margin-right: 8px;
align-self: center; // if you want it centered vertically
}
</code></pre>
<p>Virtually all browsers support flex box now. <a href="https://caniuse.com/#feat=flexbox" rel="nofollow noreferrer">https://caniuse.com/#feat=flexbox</a></p>
<p>As an aside, bootstrap 4 no longer does glyphicons natively (though there's nothing stopping you from including the glyphicons library manually--or more commonly nowadays, fontawesome), but it does include display classes natively. You can do all this without any CSS. <a href="http://jsfiddle.net/0vzmmn0v/292/" rel="nofollow noreferrer">Bootstrap 4 jsfiddle</a></p>
<pre class="lang-html prettyprint-override"><code><div class="container">
<div class="card bg-light mt-4">
<div class="card-header">
<h3>
Bootstrap 4
</h3>
</div>
<div class="card-body">
<div class="alert alert-warning d-flex flex-row">
<i class="fas fa-fw fa-exclamation-circle mr-3 align-self-center"></i>
<div>
My message here. Lots of text for several lines! My message here. Lots of text for several lines! My message here. Lots of text for several lines! My message here. Lots of text for several lines!
</div>
</div>
<div class="alert alert-info d-flex flex-row">
<i class="fas fa-fw fa-info-circle mr-3 mt-1"></i>
<div>
My message here. Lots of text for several lines! My message here. Lots of text for several lines! My message here. Lots of text for several lines! My message here. Lots of text for several lines!
</div>
</div>
</div>
</div>
</div>
</code></pre>
<p>To not center the icon vertically, simply remove the icons' <code>align-self-center</code> class. You might need to fiddle with the top margin to align it well with the text using the <code>mt-*</code> classes. <code>mt-1</code> worked well for this example.</p> |
677,021 | Emacs: regular expression replacing to change case | <p>Every once in a while I want to replace all instances of values like:</p>
<pre><code><BarFoo>
</code></pre>
<p>with</p>
<pre><code><barfoo>
</code></pre>
<p>i.e. do a regular expression replace of all things inside angle brackets with its lowercase equivalent.</p>
<p>Anyone got a nice snippet of Lisp that does this? It's safe to assume that we're dealing with just ASCII values. Bonus points for anything that is generic enough to take a full regular expression, and doesn't just handle the angle brackets example. Even more bonus points to an answer which just uses <code>M-x query-replace-regexp</code>.</p>
<p>Thanks,</p>
<p>Dom</p> | 677,033 | 3 | 0 | null | 2009-03-24 11:33:07.86 UTC | 17 | 2021-09-05 19:18:47.19 UTC | 2012-03-11 22:29:26.133 UTC | null | 133 | Dominic Rodger | 20,972 | null | 1 | 59 | regex|emacs|replace | 15,325 | <p>Try <code>M-x query-replace-regexp</code> with <code>"<\([^>]+\)>"</code> as the search string and <code>"<\,(downcase \1)>"</code> as the replacement.</p>
<p>This should work for Emacs 22 and later, see this <a href="http://steve-yegge.blogspot.com/2006/06/shiny-and-new-emacs-22.html" rel="noreferrer">Steve Yegge blog post</a> for more details on how Lisp expressions can be used in the replacement string.</p>
<p>For earlier versions of Emacs you could try something like this:</p>
<pre><code>(defun tags-to-lower-case ()
(interactive)
(save-excursion
(goto-char (point-min))
(while (re-search-forward "<[^>]+>" nil t)
(replace-match (downcase (match-string 0)) t))))
</code></pre> |
22,132,970 | Add item to arraylist if it does not already exist in list | <p>Hi I have a listview showing an arraylist, when an item is clicked it is added to another arraylist and displayed in another activity. What is my problem? I want that if an item (eg a dog) I touch once, is added to the second activity, and it shows. But if I were to touch the item (dog) is not added again. </p>
<p>We would say that I want to check if it exists, not add. </p>
<p>I've tried so, but without success.</p>
<pre><code>if (page2 == null)
{
page2 = (ListView) LayoutInflater.from(Local_mostrar_bebidaActivity.this).inflate(R.layout.page_two_viewpager_listview, null);
page2.setAdapter(adapterlistvMenuVINOSespumosos);
page2.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (MiPedidoActivity.itemsListVMiPedido.contains( position)){}
else
MiPedidoActivity.itemsListVMiPedido.add(itemsListVMenuVINOSespumosos.get(position));
}});
}
page = page2;
break;
</code></pre>
<p>Any ideas?</p> | 22,133,069 | 1 | 0 | null | 2014-03-02 20:26:13.813 UTC | 2 | 2014-03-02 20:46:36.073 UTC | 2014-03-02 20:41:26.847 UTC | null | 616,460 | null | 3,224,192 | null | 1 | 26 | java|android | 95,428 | <p>You have:</p>
<pre><code>if (MiPedidoActivity.itemsListVMiPedido.contains( position)){}
else
MiPedidoActivity.itemsListVMiPedido.add(itemsListVMenuVINOSespumosos.get(position));
</code></pre>
<p>You are checking if <code>itemsListVMiPedido</code> contains the integer, <code>position</code>, but you are adding <code>itemsListVMenuVINOSespumosos.get(position)</code> to the list. You need to check if the list contains them <em>item</em>, not the index (think of it exactly like what you are trying to do: "do not add item to list if list already contains <em>item</em>). You probably mean something like this (I just made up <code>Item</code> for example, use whatever class your objects are):</p>
<pre><code>Item item = itemsListVMenuVINOSespumosos.get(position);
if (MiPedidoActivity.itemsListVMiPedido.contains(item)) { // <- look for item!
// ... item already in list
} else {
MiPedidoActivity.itemsListVMiPedido.add(item);
}
</code></pre>
<p>By the way, as a suggestion, if your item classes have <code>equals()</code> and <code>hashCode()</code> properly implemented, consider a <a href="http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashSet.html"><code>LinkedHashSet</code></a> (which will preserve insertion order but will not allow duplicates). There are other <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Set.html"><code>Set</code></a> implementations that may be useful too (e.g. <code>TreeSet</code> if your items implement <code>Comparable</code>), depending on your ordering/sorting requirements.</p> |
36,490,270 | How to make a UIView have an effect of transparent gradient? | <p>I want to make a <code>UIView</code> have an effect of transparent gradient from the middle to the left and right. Like in this example:</p>
<p><img src="https://i.stack.imgur.com/7Svho.jpg" alt="enter image description here"></p>
<p>The word <code>籍</code> has the desired effect. This view is achieved by the class <a href="https://github.com/cbpowell/MarqueeLabel-Swift" rel="noreferrer">MarqueeLabel</a>. I examined the source code, it is likely implemented by class <code>CALayer</code>. </p> | 36,490,361 | 5 | 1 | null | 2016-04-08 02:00:47.777 UTC | 9 | 2020-05-04 03:56:01.68 UTC | 2016-04-08 02:18:13.15 UTC | null | 3,266,847 | null | 6,119,149 | null | 1 | 28 | ios|swift|uiview|gradient | 17,766 | <p>You can use <code>CAGradientLayer</code> as following.</p>
<pre><code>gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = baseView.bounds;
gradientLayer.startPoint = CGPointMake(0.5,0.0);
gradientLayer.endPoint = CGPointMake(0.5,1.0);
gradientLayer.locations = @[@(0.0), @(0.2), @(1.0)];
gradientLayer.colors = @[(id)[UIColor colorWithWhite:1.0 alpha:0.9].CGColor,
(id)[UIColor colorWithWhite:1.0 alpha:0.3].CGColor,
(id)[UIColor colorWithWhite:1.0 alpha:0.0].CGColor];
[baseView.layer addSublayer:gradientLayer];
</code></pre>
<p><code>CAGradientLayer</code> supports several properties to make natural gradient, such as setting gradient direction by <code>startPoint</code> and <code>endPoint</code>, changing color curve by <code>locations</code> and <code>colors</code>. </p>
<p>You also make a transparent effect by using alpha channel of color.</p> |
35,272,832 | SystemJS - moment is not a function | <p>I'm using <code>JSPM</code>, <code>AngularJS</code>, <code>TypeScript</code>, <code>SystemJS</code> and <code>ES6</code> and my project is running pretty well... unless I try to use momentJS.</p>
<p>This is the error I get:</p>
<blockquote>
<p>TypeError: moment is not a function</p>
</blockquote>
<p>This is part of the code:</p>
<pre><code>import * as moment from 'moment';
</code></pre>
<p>More:</p>
<pre><code>var momentInstance = moment(value);
</code></pre>
<p>If I debug it, moment is an object not a function:</p>
<p><a href="https://i.stack.imgur.com/Z2aCv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Z2aCv.png" alt="enter image description here"></a></p>
<p>This is what my moment.js JSPM package looks like:</p>
<pre><code>module.exports = require("npm:[email protected]/moment.js");
</code></pre>
<p>I've read a lot and couldn't find a way to solve this... any ideas? </p>
<p>Some things I've read/tried:</p>
<p><a href="https://stackoverflow.com/questions/33938561/how-to-use-momentjs-in-typescript-with-systemjs">How to use momentjs in TypeScript with SystemJS?</a></p>
<p><a href="https://github.com/angular-ui/ui-calendar/issues/154" rel="noreferrer">https://github.com/angular-ui/ui-calendar/issues/154</a></p>
<p><a href="https://github.com/jkuri/ng2-datepicker/issues/5" rel="noreferrer">https://github.com/jkuri/ng2-datepicker/issues/5</a></p>
<p><a href="https://stackoverflow.com/questions/32987273/typescript-module-systems-on-momentjs-behaving-strangely">Typescript module systems on momentJS behaving strangely</a></p>
<p><a href="https://github.com/dbushell/Pikaday/issues/153" rel="noreferrer">https://github.com/dbushell/Pikaday/issues/153</a></p>
<p>Thanks!</p> | 35,273,239 | 5 | 2 | null | 2016-02-08 15:09:14.617 UTC | 7 | 2020-05-05 08:06:13.267 UTC | 2017-05-23 12:02:39.19 UTC | null | -1 | null | 578,808 | null | 1 | 45 | javascript|angularjs|momentjs|systemjs | 46,402 | <p>Simply remove the grouping (<code>* as</code>) from your import statement:</p>
<pre><code>import moment from 'moment';
</code></pre>
<p>Without digging too deeply in to the <a href="https://github.com/moment/moment/">source code</a>, it looks like <code>moment</code> usually exports a function, that has all kinds of methods and other properties attached to it.</p>
<p>By using <code>* as</code>, you're effectively grabbing all those properties and attaching them to a <em>new</em> object, destroying the original function. Instead, you just want the chief export (<code>export default</code> in ES6, <code>module.exports</code> object in Node.js).</p>
<p>Alternatively, you could do</p>
<pre><code>import moment, * as moments from 'moment';
</code></pre>
<p>to get the moment function <em>as</em> <code>moment</code>, and all the other properties on an object called <code>moments</code>. This makes a little less sense when converting ES5 exports like this to ES6 style, because <code>moment</code> will retain the same properties.</p> |
34,933,594 | Angular2 parse string to html | <p>I'm importing rss items where in description there is a lot of html code (links, paragraphs, etc...). When I'm viewing it in component's view like:</p>
<pre><code>{{rss.description}}
</code></pre>
<p>the output in site is like:</p>
<pre><code><a href="http://link.com">Something</a> <p>Long text</p>
</code></pre>
<p>How can I quickly and easy parse it to html? I don't want to cross it with jQuery. Thank you</p> | 34,933,626 | 2 | 2 | null | 2016-01-21 20:22:42.567 UTC | 6 | 2021-04-17 13:13:58.69 UTC | null | null | null | null | 3,246,930 | null | 1 | 44 | html|parsing|angular | 29,797 | <p>Not sure if I understand your question correctly, but this might be what you want</p>
<pre><code><div [innerHTML]="rss.description"></div>
</code></pre>
<p>See also <a href="https://stackoverflow.com/questions/37076867/in-rc-1-some-styles-cant-be-added-using-binding-syntax">In RC.1 some styles can't be added using binding syntax</a> for how to allow "unsafe" HTML.</p> |
28,768,285 | Check text file content in PowerShell | <p>The <strong>PowerShell</strong> command</p>
<pre><code>Get-ADFSRelyingPartyTrust | select Name | out-file C:\listOfNames.txt
</code></pre>
<p>generates a file as follows:</p>
<pre><code>Name
----
AustriaRP
BahamasRP
BrazilRP
CanadaRP
[...]
</code></pre>
<p>Now, how can I check if <code>BrazilRP</code> has been extracted and <code>C:\listOfNames.txt</code> contains it?</p> | 28,769,555 | 3 | 1 | null | 2015-02-27 15:13:31.9 UTC | 0 | 2020-03-06 12:44:44.65 UTC | 2018-09-05 16:48:05.693 UTC | null | 63,550 | null | 2,274,686 | null | 1 | 2 | powershell | 39,577 | <p>I found a solution (but thanks to <strong>PiotrWolkowski</strong> to suggest me the <code>Get-Content</code> function):</p>
<pre><code>$file = Get-Content "C:\listOfNames.txt"
$containsWord = $file | %{$_ -match "BrazilRP"}
if ($containsWord -contains $true) {
Write-Host "There is!"
} else {
Write-Host "There ins't!"
}
</code></pre> |
28,587,698 | What's the difference between placing "mut" before a variable name and after the ":"? | <p>Here are two function signatures I saw in the Rust documentation:</p>
<pre><code>fn modify_foo(mut foo: Box<i32>) { *foo += 1; *foo }
fn modify_foo(foo: &mut i32) { *foo += 1; *foo }
</code></pre>
<p>Why the different placement of <code>mut</code>?</p>
<p>It seems that the first function could also be declared as</p>
<pre><code>fn modify_foo(foo: mut Box<i32>) { /* ... */ }
</code></pre> | 28,587,902 | 4 | 1 | null | 2015-02-18 15:46:54.41 UTC | 44 | 2022-07-06 00:02:34.557 UTC | 2019-03-18 11:01:36.397 UTC | null | 493,729 | null | 690,061 | null | 1 | 122 | variables|syntax|reference|rust|mutable | 16,801 | <p><code>mut foo: T</code> means you have a variable called <code>foo</code> that is a <code>T</code>. You are allowed to change what the variable <strong>refers to</strong>:</p>
<pre><code>let mut val1 = 2;
val1 = 3; // OK
let val2 = 2;
val2 = 3; // error: re-assignment of immutable variable
</code></pre>
<p>This also lets you modify fields of a struct that you own:</p>
<pre><code>struct Monster { health: u8 }
let mut orc = Monster { health: 93 };
orc.health -= 54;
let goblin = Monster { health: 28 };
goblin.health += 10; // error: cannot assign to immutable field
</code></pre>
<p><code>foo: &mut T</code> means you have a variable that refers to (<code>&</code>) a value and you are allowed to change (<code>mut</code>) the <strong>referred value</strong> (including fields, if it is a struct):</p>
<pre><code>let val1 = &mut 2;
*val1 = 3; // OK
let val2 = &2;
*val2 = 3; // error: cannot assign to immutable borrowed content
</code></pre>
<p>Note that <code>&mut</code> only makes sense with a reference - <code>foo: mut T</code> is not valid syntax. You can also combine the two qualifiers (<code>let mut a: &mut T</code>), when it makes sense.</p> |
28,782,394 | How to get osx shell script to show colors in echo | <p>I'm trying to add color output to my errors in a bash script that I have running on a mac. The problem is the colors are not working. I created the simplest of scripts to demonstrate that it does not work:</p>
<pre><code>#!/bin/bash
echo -e "\e[1;31m This is red text \e[0m"
</code></pre>
<p>However, when i run it, I see no colors at all, as shown in this image. The color output of the ls command is working fine however.</p>
<p><img src="https://i.stack.imgur.com/kgbnY.png" alt="enter image description here"></p> | 28,782,466 | 5 | 1 | null | 2015-02-28 13:44:48.76 UTC | 12 | 2022-06-14 12:35:07.973 UTC | null | null | null | null | 532,685 | null | 1 | 62 | macos|bash|shell|echo | 41,182 | <p>OSX ships with an old version of Bash that does not support the <code>\e</code> escape character. Use <code>\x1B</code> or update Bash (<code>brew install bash</code>).</p>
<p>Even better, though, would be to use <code>tput</code>.</p> |
24,393,944 | Uniqueness in DynamoDB secondary index | <p><strong>Question:</strong></p>
<p>DynamoDB tables with a primary key that is a composite hash-range key are unique. Does this extend to secondary indices too?</p>
<p><strong>Example:</strong></p>
<p>I have a comments DynamoDB table with a <strong>post_id</strong> primary key and <strong>comment_id</strong> range key.
Additionally there's a local secondary index with a <strong>date-user_id</strong> range key.</p>
<p>Each entry is a comment a user has left on post. The purpose of the secondary index is to count how many unique users left a comment on a post on a specific day.</p>
<p><strong>Entry 1</strong>:
post_id: 1
comment_id: 1
date-user_id: 2014_06_24-1</p>
<p><strong>Entry 2</strong>:
post_id: 1
comment_id: 2
date-user_id: 2014_06_24-1</p>
<p><strong>Entry 3</strong>:
post_id: 1
comment_id: 3
date-user_id: 2014_06_24-2</p>
<p>When I do a query specifying the secondary index, and pass in a condition of post_id equals 1 and a date-user_id equals 2014_06_24-1, I'm getting a count of 2 and I'm expecting a count of 1.</p>
<p>Why does the secondary index have two entries with the same primary key/range key.</p> | 24,395,308 | 5 | 0 | null | 2014-06-24 18:38:17.233 UTC | 2 | 2022-06-02 04:41:29.657 UTC | 2019-11-26 13:33:40.827 UTC | null | 788,833 | null | 3,772,393 | null | 1 | 32 | amazon-web-services|amazon-dynamodb | 26,234 | <p>Each item in a Local Secondary Index (LSI) has a 1:1 relationship with the corresponding item in the table. In the example above, while entry 1 and entry 2 in the LSI have the same range key value, the item in the table they point to is different. Hence Index keys ( hash or hash+range) are not unique. </p>
<p>Global Secondary Index (GSI) are similar to LSI in this aspect. Every GSI item contains the table hash and range keys (of the corresponding item). More details are available at <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html#GSI.Projections" rel="nofollow">http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html#GSI.Projections</a></p> |
24,412,418 | What's the working directory in Jenkins after executing a shell command box? | <p>I'm looking at a Jenkins job and trying to understand it.</p>
<p>I have an <strong>Execute shell</strong> command box in my <strong>Build</strong> section:</p>
<pre><code>> mkdir mydir
> cd mydir
>
> svn export --force https://example.com/repo/mydir .
</code></pre>
<p>When Jenkins is done executing that command, and moves on to the next build step, what is its working directory?
<code>workspece-root/</code> or <code>workspace-root/mydir</code> ?</p>
<p>As the next step, I have <strong>Invoke top-level Maven targets</strong> (still in the <strong>Build</strong> section).</p>
<p>What I really want to know is: why does that execute successfully?<br/>
Is it because Jenkins automatically moves back to the <code>workspace-root/</code> folder after executing a shell command box, or is it because the next job is a "top-level" job, and Jenkins therefore changes back to the <code>workspace-root/</code>?</p> | 24,417,132 | 3 | 0 | null | 2014-06-25 15:10:05.287 UTC | 2 | 2019-01-04 09:55:30.65 UTC | null | null | null | null | 2,018,047 | null | 1 | 15 | jenkins|working-directory | 52,168 | <p>Each <code>build step</code> is a separate process that Jenkins spawns off. They don't share anything, neither current directory, nor environment variables set/changed within the <code>build step</code>. Each new <code>build step</code> starts by spawning a new process off the parent process (the one running Jenkins)</p>
<p>It's not that Jenkins "move back" to <code>$WORKSPACE</code>. It's that Jenkins <strong>discards</strong> the previous session.</p> |
42,746,828 | jq - How to filter a json that does not contain | <p>I have an aws query that I want to filter in <code>jq</code>.
I want to filter all the <code>imageTags</code> that <strong>don't</strong> end with "latest"</p>
<p>So far I did this but it filters things containing "latest" while I want to filter things not containing "latest" (or not ending with "latest")</p>
<pre><code>aws ecr describe-images --repository-name <repo> --output json | jq '.[]' | jq '.[]' | jq "select ((.imagePushedAt < 14893094695) and (.imageTags[] | contains(\"latest\")))"
</code></pre>
<p>Thanks</p> | 42,747,910 | 4 | 2 | null | 2017-03-12 11:26:42.123 UTC | 2 | 2022-09-13 21:00:43.81 UTC | 2018-12-23 09:48:50.593 UTC | null | 345,959 | null | 2,717,853 | null | 1 | 64 | json|jq | 53,443 | <p>You can use <code>not</code> to reverse the logic</p>
<pre><code>(.imageTags[] | contains(\"latest\") | not)
</code></pre>
<p>Also, I'd imagine you can simplify your pipeline into a single <code>jq</code> call.</p> |
35,923,744 | Pass enums in angular2 view templates | <p>Can we use enums in an angular2 view template?</p>
<pre class="lang-html prettyprint-override"><code><div class="Dropdown" dropdownType="instrument"></div>
</code></pre>
<p>passes the string as input:</p>
<pre class="lang-js prettyprint-override"><code>enum DropdownType {
instrument,
account,
currency
}
@Component({
selector: '[.Dropdown]',
})
export class Dropdown {
@Input() public set dropdownType(value: any) {
console.log(value);
};
}
</code></pre>
<p>But how to pass an enum configuration? I want something like this in the template:</p>
<pre class="lang-html prettyprint-override"><code><div class="Dropdown" dropdownType="DropdownType.instrument"></div>
</code></pre>
<p>What would be the best practice?</p>
<p>Edited:
Created an example:</p>
<pre class="lang-js prettyprint-override"><code>import {bootstrap} from 'angular2/platform/browser';
import {Component, View, Input} from 'angular2/core';
export enum DropdownType {
instrument = 0,
account = 1,
currency = 2
}
@Component({selector: '[.Dropdown]',})
@View({template: ''})
export class Dropdown {
public dropdownTypes = DropdownType;
@Input() public set dropdownType(value: any) {console.log(`-- dropdownType: ${value}`);};
constructor() {console.log('-- Dropdown ready --');}
}
@Component({ selector: 'header' })
@View({ template: '<div class="Dropdown" dropdownType="dropdownTypes.instrument"> </div>', directives: [Dropdown] })
class Header {}
@Component({ selector: 'my-app' })
@View({ template: '<header></header>', directives: [Header] })
class Tester {}
bootstrap(Tester);
</code></pre> | 35,924,445 | 5 | 1 | null | 2016-03-10 17:50:19.763 UTC | 13 | 2022-06-29 12:29:01.213 UTC | 2019-05-17 05:14:21.663 UTC | null | 3,159,486 | null | 5,744,177 | null | 1 | 168 | enums|angular|angular2-template | 103,265 | <p>Create a property for your enum on the parent component to your component class and assign the enum to it, then reference that property in your template.</p>
<pre class="lang-js prettyprint-override"><code>export class Parent {
public dropdownTypes = DropdownType;
}
export class Dropdown {
@Input() public set dropdownType(value: any) {
console.log(value);
};
}
</code></pre>
<p>This allows you to enumerate the enum as expected in your template.</p>
<pre class="lang-html prettyprint-override"><code><div class="Dropdown" [dropdownType]="dropdownTypes.instrument"></div>
</code></pre> |
6,214,201 | Best practices for loading page content via AJAX request in Rails3? | <p>Suppose you have a page with two columns of content. For whatever reason, you wish to retrieve the HTML content of one of those columns after the page has loaded, via an AJAX request. The user does not need to take an action to make the content load (no link clicking or form submissions), it just happens automatically.</p>
<p>I can easily do this by returning an empty placeholder div in the main response</p>
<pre><code><div id="pink-dancing-elephants"></div>
</code></pre>
<p>and then add a little jQuery to the page</p>
<pre><code>$.ajax({
url: "/elephants/dancing/pink",
cache: false,
success: function(html){
$("#pink-dancing-elephants").append(html);
}
});
</code></pre>
<p>and have the action that responses to /elephants/dancing/pink return the corresponding blob of HTML.</p>
<p>This all works fine, but I'm wondering if I'm missing some Rails3 feature that would make this easier. E.g. I'm searching for the ability to be able to just put something like the following in the main view and have the rest of it happen by "magic"</p>
<pre><code><%= render :url=>"/elephants/dancing/pink", :remote => true %>
</code></pre>
<p>Am I missing something?</p> | 7,506,324 | 4 | 0 | null | 2011-06-02 11:57:34.47 UTC | 10 | 2013-05-17 14:58:35.447 UTC | 2011-06-02 13:39:30.173 UTC | null | 757,974 | null | 757,974 | null | 1 | 14 | jquery|ruby-on-rails|ajax|ruby-on-rails-3 | 17,290 | <p>I think what I originally outlined is actually the best approach.</p>
<p>First put an empty, placeholder div in your main view</p>
<pre><code><div id="recent_posts"></div>
</code></pre>
<p>and then add a little jQuery to the page</p>
<pre><code>$.ajax({
url: "/posts/recent",
cache: false,
success: function(html){
$("#recent_posts").append(html);
}
});
</code></pre>
<p>and have the action that responses to /posts/recent return the blob of HTML that you want to have fill up the div. In the action that is invoked by the AJAX request, you'll want to render with :layout => false to keep the returned blob of HTML from including the entire frame. E.g.</p>
<pre><code># posts_controller.rb
def recent
@recent_posts = #whatever
render :layout => false
end
</code></pre>
<p>This would render the template in views/posts/recent.html.erb and then the jQuery will take care of inserting the rendered contents into your placeholder div.</p> |
34,694,965 | Image recognition using TensorFlow | <p>I'm new to TensorFlow and I am looking for help on image recognition. Is there an example that showcases how to use TensorFlow to train your own digital images for image recognition like the image-net model used in the <a href="https://www.tensorflow.org/versions/master/tutorials/image_recognition/index.html#image-recognition">TensorFlow image recognition tutorial</a></p>
<p>I looked at the CIFAR-10 model training but it doesn't seem to provide examples for training your own images.</p> | 38,526,641 | 2 | 2 | null | 2016-01-09 14:55:29.783 UTC | 10 | 2019-11-19 15:54:12.65 UTC | null | null | null | null | 1,055,357 | null | 1 | 13 | python|image-recognition|tensorflow | 23,126 | <p>I would recommend using Google's trained Inception model to do image recognition.
Please refer to the example "How to Retrain Inception's Final Layer for New Categories" on tensorflow website. It is at <a href="https://www.tensorflow.org/versions/r0.9/how_tos/image_retraining/index.html" rel="noreferrer">https://www.tensorflow.org/versions/r0.9/how_tos/image_retraining/index.html</a>.</p>
<p>Using trained model is easy and can achieve reasonable accuracy. You just simply feed the model with your own data set. The last classication layer of Google's inception will be modified and we only train the last layer. For several thousand images with in several categories, it only take several hours to finish training.
Please note: in order to use the example, you have to build tensorflow from source.</p>
<p>I am using the transfer learning feature and achieving very good results. To illustrate the benefit of transfer learning, I am comparing "Transfer Learning on Trained GoogleNet" with "Build and train a 5-layer-Convnet from scratch". The classification task is done on 5000 images with 5 categories.</p>
<p><a href="https://i.stack.imgur.com/7XqIq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7XqIq.png" alt="Build a 5-layer-convet and train it from scratch"></a></p>
<p><a href="https://i.stack.imgur.com/HXEp8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HXEp8.png" alt="Use the transfer learning on the trained GoogleNet"></a></p>
<p>See this simple example: <a href="https://www.youtube.com/watch?v=QfNvhPx5Px8" rel="noreferrer">https://www.youtube.com/watch?v=QfNvhPx5Px8</a> (Build a TensorFlow Image Classifier in 5 Min)</p> |
1,434,284 | When Does Asp.Net Remove Expired Cache Items? | <p>When you add an item to the <code>System.Web.Caching.Cache</code> with an absolute expiration date, as in the following example, how does Asp.Net behave? Does it:</p>
<ol>
<li><p>Simply mark the item as expired, then execute the <code>CacheItemRemovedCallback</code> on the next access attempt?</p></li>
<li><p>Remove the item from the cache and execute the <code>CacheItemRemovedCallback</code> immediately?</p>
<pre><code>HttpRuntime.Cache.Insert(key,
new object(),
null,
DateTime.Now.AddSeconds(seconds),
Cache.NoSlidingExpiration,
CacheItemPriority.NotRemovable,
OnCacheRemove);
</code></pre></li>
</ol>
<p>MSDN appears to indicate that it happens immediately. For example, <a href="http://msdn.microsoft.com/en-us/library/ms178597(VS.80).aspx" rel="nofollow noreferrer">the "Expiration" section of the "ASP.NET Caching Overview"</a> says "ASP.NET automatically removes items from the cache when they expire." Similarly, the example from the topic <a href="http://msdn.microsoft.com/en-us/library/7kxdx246.aspx" rel="nofollow noreferrer">"How to: Notify an Application When an Item Is Removed from the Cache"</a> says "If more than 15 seconds elapses between calls to <code>GetReport</code> [a method in the example], ASP.NET removes the report from the cache."</p>
<p>Still, neither of these is unambiguous. They don't say "the callback is executed immediately" and I could conceive of how their writers might have thought option 1 above counts as 'removing' an item. So I did a quick and dirty test, and lo, it appears to be executing immediately - I get regular sixty-second callbacks even when no one is accessing my site.</p>
<p>Nonetheless, my test was quick and dirty, and in the comments to my answer to <a href="https://stackoverflow.com/questions/1395358/is-there-a-way-to-run-a-process-every-day-in-a-net-web-application-without-writi/1395447#1395447">Is there a way to run a process every day in a .Net web application without writing a windows service or SQL server jobs</a>, someone has suggested that Asp.Net actually defers removal and execution of the callback until something tries to access the cache again.</p>
<p>Can anyone settle this authoritatively or is this just considered an implementation detail?</p> | 1,442,211 | 2 | 3 | null | 2009-09-16 17:10:59.883 UTC | 11 | 2010-01-17 19:30:43.593 UTC | 2017-05-23 12:34:04.237 UTC | null | -1 | null | 47,886 | null | 1 | 23 | asp.net|caching | 10,086 | <p>Hurray for <a href="http://www.red-gate.com/products/reflector/" rel="noreferrer">Reflector</a>!</p>
<p>Expired cache items are <em>actually</em> removed (and callbacks called) when either:</p>
<p>1) Something tries to access the cache item.</p>
<p>2) The <code>ExpiresBucket.FlushExpiredItems</code> method runs and gets to item. This method is hard-coded to execute every 20 seconds (the accepted answer to the StackOverflow question <a href="https://stackoverflow.com/questions/268468/changing-frequency-of-asp-net-cache-item-expiration">Changing frequency of ASP.NET cache item expiration</a> corroborates my read of this code via Reflector). However, this has needs additional qualification (for which read on).</p>
<hr>
<p>Asp.Net maintains one cache for each CPU on the server (I'm not sure if it these represent logical or physical CPUs); each of these maintains a <code>CacheExpires</code> instance that has a corresponding <code>Timer</code> that calls its <code>FlushExpiredItems</code> method every twenty seconds.</p>
<p>This method iterates over another collection of 'buckets' of cache expiration data (an array of <code>ExpiresBucket</code> instances) serially, calling each bucket's <code>FlushExpiredItems</code> method in turn.</p>
<p><em>This method</em> (<code>ExpiresBucket.FlushExpiredItems</code>) first iterates all the cache items in the bucket and if an item is expired, marks it expired. Then (I'm grossly simplifying here) it iterates the items it has marked expired and removes them, executing the <code>CacheItemRemovedCallback</code> (actually, it calls <code>CacheSingle.Remove</code>, which calls <code>CacheInternal.DoRemove</code>, then <code>CacheSingle.UpdateCache</code>, then <code>CacheEntry.Close</code>, which actually calls the callback).</p>
<p>All of that happens serially, so there's a chance something could block the entire process and hold things up (and push the cache item's expiration back from its specified expiration time).</p>
<p>However, at this temporal resolution, with a minimum expiration interval of twenty seconds, the only part of the process that could block for a significant length of time is the execution of the <code>CacheItemRemovedCallbacks</code>. Any one of these could conceivably block a given <code>Timer</code>'s <code>FlushExpiredItems</code> thread indefinitely. (Though twenty seconds later, the <code>Timer</code> would spawn another <code>FlushExpiredItems</code> thread.)</p>
<p>To summarize, Asp.Net does not <em>guarantee</em> that it will execute callbacks at the specified time, but it will do so under some conditions. As long as the expiration intervals are more than twenty seconds apart, and as long as the cache doesn't have to execute time-consuming <code>CacheItemRemovedCallbacks</code> (globally - any callbacks could potentially interfere with any others), it can execute expiration callbacks on schedule. That will be good enough for some applications, but fall short for others.</p> |
2,023,506 | Selecting main class in a runnable jar at runtime | <p>I have two main classes in the app. When I package it to a runnable jar (using Eclipse export function) I have to select a default main class.</p>
<p>Is there a way to access the non-default main class from the jar at runtime?</p> | 2,023,544 | 2 | 0 | null | 2010-01-07 20:43:40.093 UTC | 5 | 2010-01-07 20:51:00.233 UTC | null | null | null | null | 10,523 | null | 1 | 29 | java|jar|executable-jar | 48,236 | <p>You can access both via <code>java -cp myapp.jar com.example.Main1</code> and <code>java -cp myapp.jar com.example.Main2</code>. The default main class in the jar is for when you invoke your app via <code>java -jar myapp.jar</code>. </p>
<p>See <a href="http://en.wikipedia.org/wiki/JAR_(file_format)" rel="noreferrer">JAR_(file_format)</a> for more details. When you select the main class in Eclipse this is what gets set in: <code>Main-Class: myPrograms.MyClass</code> inside of the jar manifest <code>META-INF/MANIFEST.MF</code> in side of the jar file.</p> |
46,091,924 | Python: How to drop a row whose particular column is empty/NaN? | <p>I have a csv file. I read it:</p>
<pre><code>import pandas as pd
data = pd.read_csv('my_data.csv', sep=',')
data.head()
</code></pre>
<p>It has output like:</p>
<pre><code>id city department sms category
01 khi revenue NaN 0
02 lhr revenue good 1
03 lhr revenue NaN 0
</code></pre>
<p>I want to remove all the rows where <code>sms</code> column is empty/NaN. What is efficient way to do it?</p> | 46,091,980 | 2 | 1 | null | 2017-09-07 08:49:34.7 UTC | 13 | 2017-10-23 10:12:53.903 UTC | 2017-09-07 08:54:06.003 UTC | null | 4,909,087 | null | 7,280,300 | null | 1 | 39 | python|pandas|dataframe | 56,830 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html" rel="noreferrer"><code>dropna</code></a> with parameter <code>subset</code> for specify column for check <code>NaN</code>s:</p>
<pre><code>data = data.dropna(subset=['sms'])
print (data)
id city department sms category
1 2 lhr revenue good 1
</code></pre>
<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="noreferrer"><code>boolean indexing</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.notnull.html" rel="noreferrer"><code>notnull</code></a>:</p>
<pre><code>data = data[data['sms'].notnull()]
print (data)
id city department sms category
1 2 lhr revenue good 1
</code></pre>
<p>Alternative with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="noreferrer"><code>query</code></a>:</p>
<pre><code>print (data.query("sms == sms"))
id city department sms category
1 2 lhr revenue good 1
</code></pre>
<p><strong>Timings</strong></p>
<pre><code>#[300000 rows x 5 columns]
data = pd.concat([data]*100000).reset_index(drop=True)
In [123]: %timeit (data.dropna(subset=['sms']))
100 loops, best of 3: 19.5 ms per loop
In [124]: %timeit (data[data['sms'].notnull()])
100 loops, best of 3: 13.8 ms per loop
In [125]: %timeit (data.query("sms == sms"))
10 loops, best of 3: 23.6 ms per loop
</code></pre> |
32,253,362 | How do I build a single js file for AWS Lambda nodejs runtime | <p>We are working on a <a href="https://github.com/jaws-stack/JAWS/tree/v1.0">project/framework</a> that aids in deploying and maintaining code in AWS Lambda. I want to build/bundle all node.js code for a lambda function into one js file because:</p>
<ul>
<li>Smaller codebases help with lambda cold start issues</li>
<li>Lambda has code zip size limit of 50MB</li>
</ul>
<p>We don't want to create a custom bundler to do this because there are many options already out there (systemjs,browserify,webpack etc). HOWEVER we are concerned with issues with some node modules not playing well with bundlers/builders.</p>
<p>Specifically <code>aws-sdk</code> has <a href="https://github.com/aws/aws-sdk-js/issues/603">known issues with webpack</a>, says it has <a href="http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/browser-building.html#Building_the_SDK_as_a_Dependency_with_Browserify">browserify support</a> but I've talked to people who have had issues with browserify'ing aws-sdk</p>
<p>We want to pick an existing bundler (or 2), but we want to make sure it works for as many modules/code as possible. We are trying to create a plugin ecosystem for JAWS, so getting this right is important (don't want to turn people off because module X they use wont bundle).</p>
<p>Questions:</p>
<ol>
<li>How would I go about bundling/building to satisfy these constraints?</li>
<li>Is there any guidelines we can give to consumers of our product to ensure the code they write/use will bundle? Ex: Dynamic require()s cause issues AFAIK.</li>
</ol> | 41,488,237 | 4 | 1 | null | 2015-08-27 15:20:33.47 UTC | 11 | 2017-01-05 15:04:24.283 UTC | null | null | null | null | 563,420 | null | 1 | 18 | javascript|browserify|webpack|aws-lambda|systemjs | 4,007 | <p><a href="https://github.com/aws/aws-sdk-js" rel="nofollow noreferrer">aws-sdk-js</a> now officially <a href="https://github.com/aws/aws-sdk-js/issues/696" rel="nofollow noreferrer">supports browserify</a>. You can why this is a great thing <a href="https://rynop.wordpress.com/2016/11/01/aws-sdk-for-javascript-now-fully-componentized/" rel="nofollow noreferrer">on my blog</a>.</p>
<p>I have created a serverless plugin called <a href="https://github.com/doapp-ryanp/serverless-plugin-browserify/blob/master/README.md" rel="nofollow noreferrer">serverless-plugin-browserify</a> that will do all the heavy lifting with very minimal configuration.</p>
<p>To answer the question specifically, I solved the problem with this browserify config:</p>
<pre><code>{
disable: false, //Not an official option, used as internal option to skip browserify
exclude: [], //Not an option, but will use for setting browserify.exclude() if defined in yml
ignore: [], //Not an option, but will use for setting browserify.ignore() if defined in yml
basedir: this.serverless.config.servicePath,
entries: [],
standalone: 'lambda',
browserField: false, // Setup for node app (copy logic of --node in bin/args.js)
builtins: false,
commondir: false,
ignoreMissing: true, // Do not fail on missing optional dependencies
detectGlobals: true, // We don't care if its slower, we want more mods to work
insertGlobalVars: { // Handle process https://github.com/substack/node-browserify/issues/1277
//__filename: insertGlobals.lets.__filename,
//__dirname: insertGlobals.lets.__dirname,
process: function() {
},
},
debug: false,
}
</code></pre>
<p>You can see my full code <a href="https://github.com/doapp-ryanp/serverless-plugin-browserify/tree/master/lib" rel="nofollow noreferrer">here</a> with a complete example <a href="https://github.com/doapp-ryanp/serverless-plugin-browserify/tree/master/examples/aws-sdk-parts" rel="nofollow noreferrer">here</a></p> |
6,019,765 | How do I convert a List<interface> to List<concrete>? | <p>I have an interface defined as:</p>
<pre><code>public interface MyInterface {
object foo { get; set; };
}
</code></pre>
<p>and a class that implements that interface:</p>
<pre><code>public class MyClass : MyInterface {
object foo { get; set; }
}
</code></pre>
<p>I then create a function that returns a ICollection like so:</p>
<pre><code>public ICollection<MyClass> Classes() {
List<MyClass> value;
List<MyInterface> list = new List<MyInterface>(
new MyInterface[] {
new MyClass {
ID = 1
},
new MyClass {
ID = 1
},
new MyClass {
ID = 1
}
});
value = new List<MyClass>((IEnumerable<MyClass>) list);
return value;
}
</code></pre>
<p>It would compile but would throw a</p>
<blockquote>
<p>Unable to cast object of type
'System.Collections.Generic.List<code>1[MyInterface]'
to type
'System.Collections.Generic.IEnumerable</code>1[MyClass]'.</p>
</blockquote>
<p>exception. What am I doing wrong?</p> | 6,019,805 | 5 | 0 | null | 2011-05-16 15:37:54.02 UTC | 5 | 2020-09-30 19:08:33 UTC | null | null | null | null | 160,204 | null | 1 | 44 | c#|generics|interface | 29,806 | <p>A <code>List<MyInterface></code> cannot be converted to a <code>List<MyClass></code> in general, because the first list might contain objects that implement <code>MyInterface</code> but which aren't actually objects of type <code>MyClass</code>.</p>
<p>However, since in your case you know how you constructed the list and can be sure that it contains only <code>MyClass</code> objects, you can do this using Linq:</p>
<pre><code>return list.ConvertAll(o => (MyClass)o);
</code></pre> |
5,731,863 | Mapping a numeric range onto another | <p>Math was never my strong suit in school :(</p>
<pre><code>int input_start = 0; // The lowest number of the range input.
int input_end = 254; // The largest number of the range input.
int output_start = 500; // The lowest number of the range output.
int output_end = 5500; // The largest number of the range output.
int input = 127; // Input value.
int output = 0;
</code></pre>
<p>How can I convert the input value to the corresponding output value of that range?</p>
<p>For example, an input value of "0" would equal an output value of "500", an input value of "254" would equal an output value of "5500". I can't figure out how to calculate an output value if an input value is say 50 or 101.</p>
<p>I'm sure it's simple, I can't think right now :)</p>
<p>Edit: I just need whole numbers, no fractions or anything.</p> | 5,732,390 | 6 | 0 | null | 2011-04-20 14:21:33.84 UTC | 67 | 2022-03-25 14:13:12.957 UTC | 2020-06-16 06:31:20.847 UTC | null | 3,796,039 | null | 695,648 | null | 1 | 118 | c|math|arduino | 123,778 | <p>Let's forget the math and try to solve this intuitively.</p>
<p>First, if we want to map input numbers in the range [<code>0</code>, <code>x</code>] to output range [<code>0</code>, <code>y</code>], we just need to scale by an appropriate amount. 0 goes to 0, <code>x</code> goes to <code>y</code>, and a number <code>t</code> will go to <code>(y/x)*t</code>.</p>
<p>So, let's reduce your problem to the above simpler problem.</p>
<p>An input range of [<code>input_start</code>, <code>input_end</code>] has <code>input_end - input_start + 1</code> numbers. So it's equivalent to a range of [<code>0</code>, <code>r</code>], where <code>r = input_end - input_start</code>.</p>
<p>Similarly, the output range is equivalent to [<code>0</code>, <code>R</code>], where <code>R = output_end - output_start</code>.</p>
<p>An input of <code>input</code> is equivalent to <code>x = input - input_start</code>. This, from the first paragraph will translate to <code>y = (R/r)*x</code>. Then, we can translate the <code>y</code> value back to the original output range by adding <code>output_start</code>: <code>output = output_start + y</code>.</p>
<p>This gives us:</p>
<pre><code>output = output_start + ((output_end - output_start) / (input_end - input_start)) * (input - input_start)
</code></pre>
<p>Or, another way:</p>
<pre><code>/* Note, "slope" below is a constant for given numbers, so if you are calculating
a lot of output values, it makes sense to calculate it once. It also makes
understanding the code easier */
slope = (output_end - output_start) / (input_end - input_start)
output = output_start + slope * (input - input_start)
</code></pre>
<p>Now, this being C, and division in C truncates, you should try to get a more accurate answer by calculating things in floating-point:</p>
<pre><code>double slope = 1.0 * (output_end - output_start) / (input_end - input_start)
output = output_start + slope * (input - input_start)
</code></pre>
<p>If wanted to be even more correct, you would do a rounding instead of truncation in the final step. You can do this by writing a simple <code>round</code> function:</p>
<pre><code>#include <math.h>
double round(double d)
{
return floor(d + 0.5);
}
</code></pre>
<p>Then:</p>
<pre><code>output = output_start + round(slope * (input - input_start))
</code></pre> |
6,116,474 | How to find if an array contains a specific string in JavaScript/jQuery? | <p>Can someone tell me how to detect if <code>"specialword"</code> appears in an array? Example:</p>
<pre><code>categories: [
"specialword"
"word1"
"word2"
]
</code></pre> | 15,276,975 | 7 | 4 | null | 2011-05-24 20:31:35.483 UTC | 107 | 2022-08-13 07:30:17.003 UTC | 2017-11-08 15:36:39.13 UTC | null | 475,890 | null | 475,890 | null | 1 | 718 | javascript|jquery|arrays|string | 1,142,187 | <p>You really don't need jQuery for this.</p>
<pre><code>var myarr = ["I", "like", "turtles"];
var arraycontainsturtles = (myarr.indexOf("turtles") > -1);
</code></pre>
<blockquote>
<p><strong>Hint</strong>: indexOf returns a number, representing the position where the specified searchvalue occurs for the first time, or -1 if it never
occurs</p>
</blockquote>
<p>or</p>
<pre><code>function arrayContains(needle, arrhaystack)
{
return (arrhaystack.indexOf(needle) > -1);
}
</code></pre>
<p>It's worth noting that <code>array.indexOf(..)</code> is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Browser_compatibility" rel="noreferrer">not supported in IE < 9</a>, but jQuery's <code>indexOf(...)</code> function will work even for those older versions. </p> |
55,934,019 | Randomness of Python's random | <p>I'm using Python to generate images using dashed lines for stippling. The period of the dashing is constant, what changes is dash/space ratio. This produces something like this:</p>
<p><a href="https://i.stack.imgur.com/zrApk.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/zrApk.jpg" alt="enter image description here"></a></p>
<p>However in that image the dashing has a uniform origin and this creates unsightly vertical gutters. So I tried to randomize the origin to remove the gutters. This sort of works but there is an obvious pattern:</p>
<p><a href="https://i.stack.imgur.com/7ugSP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7ugSP.png" alt="enter image description here"></a></p>
<p>Wondering where this comes from I made a very simple test case with stacked dashed straight lines: </p>
<ul>
<li>dash ratio: 50%</li>
<li>dash period 20px</li>
<li>origin shift from -10px to +10px using <code>random.uniform(-10.,+10.)</code>(*) (after an initial <code>random.seed()</code></li>
</ul>
<p><a href="https://i.stack.imgur.com/lDUtK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lDUtK.png" alt="enter image description here"></a></p>
<p>And with added randomness:</p>
<p><a href="https://i.stack.imgur.com/8nMjm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8nMjm.png" alt="enter image description here"></a> </p>
<p>So there is still pattern. What I don't understand is that to get a visible gutter you need to have 6 or 7 consecutive values falling in the same range (says, half the total range), which should be a 1/64 probability but seems to happen a lot more often in the 200 lines generated.</p>
<p>Am I misunderstanding something? Is it just our human brain which is seeing patterns where there is none? Could there be a better way to generate something more "visually random" (python 2.7, and preferably without installing anything)? </p>
<p>(*) partial pixels are valid in that context</p>
<p>Annex: the code I use (this is a Gimp script):</p>
<pre><code>#!/usr/bin/env python
# -*- coding: iso-8859-15 -*-
# Python script for Gimp (requires Gimp 2.10)
# Run on a 400x400 image to see something without having to wait too much
# Menu entry is in "Test" submenu of image menubar
import random,traceback
from gimpfu import *
def constant(minShift,maxShift):
return 0
def triangle(minShift,maxShift):
return random.triangular(minShift,maxShift)
def uniform(minShift,maxShift):
return random.uniform(minShift,maxShift)
def gauss(minShift,maxShift):
return random.gauss((minShift+maxShift)/2,(maxShift-minShift)/2)
variants=[('Constant',constant),('Triangle',triangle),('Uniform',uniform),('Gauss',gauss)]
def generate(image,name,generator):
random.seed()
layer=gimp.Layer(image, name, image.width, image.height, RGB_IMAGE,100, LAYER_MODE_NORMAL)
image.add_layer(layer,0)
layer.fill(FILL_WHITE)
path=pdb.gimp_vectors_new(image,name)
# Generate path, horizontal lines are 2px apart,
# Start on left has a random offset, end is on the right edge right edge
for i in range(1,image.height, 2):
shift=generator(-10.,10.)
points=[shift,i]*3+[image.width,i]*3
pdb.gimp_vectors_stroke_new_from_points(path,0, len(points),points,False)
pdb.gimp_image_add_vectors(image, path, 0)
# Stroke the path
pdb.gimp_context_set_foreground(gimpcolor.RGB(0, 0, 0, 255))
pdb.gimp_context_set_stroke_method(STROKE_LINE)
pdb.gimp_context_set_line_cap_style(0)
pdb.gimp_context_set_line_join_style(0)
pdb.gimp_context_set_line_miter_limit(0.)
pdb.gimp_context_set_line_width(2)
pdb.gimp_context_set_line_dash_pattern(2,[5,5])
pdb.gimp_drawable_edit_stroke_item(layer,path)
def randomTest(image):
image.undo_group_start()
gimp.context_push()
try:
for name,generator in variants:
generate(image,name,generator)
except Exception as e:
print e.args[0]
pdb.gimp_message(e.args[0])
traceback.print_exc()
gimp.context_pop()
image.undo_group_end()
return;
### Registration
desc="Python random test"
register(
"randomize-test",desc,'','','','',desc,"*",
[(PF_IMAGE, "image", "Input image", None),],[],
randomTest,menu="<Image>/Test",
)
main()
</code></pre> | 55,935,432 | 4 | 7 | null | 2019-05-01 09:16:03.653 UTC | 14 | 2019-05-02 06:49:50.287 UTC | 2019-05-01 10:05:05.94 UTC | null | 6,378,557 | null | 6,378,557 | null | 1 | 71 | python|random | 7,940 | <p>Think of it like this: a gutter is perceptible until it is obstructed (or almost so). This only happens when two successive lines are almost completely out of phase (with the black segments in the first line lying nearly above the white segments in the next). Such extreme situations only happens about one out of every 10 rows, hence the visible gutters which seem to extend around 10 rows before being obstructed.</p>
<p>Looked at another way -- if you print out the image, there really are longish white channels through which you can easily draw a line with a pen. Why should your mind not perceive them?</p>
<p>To get better visual randomness, find a way to make successive lines <em>dependent</em> rather than independent in such a way that the almost-out-of-phase behavior appears more often.</p> |
25,214,084 | Can't get ASCII art to echo to console | <p>I'm new to Bash scripting, and this here is just puzzling to me. I'm adding ASCII art to a project, and can't seem to figure out how to escape certain characters. Would someone please help me get the following code below to work? </p>
<p>Whenever I tried adding slashes as escape characters to fix the errors, the slashes also wound up printing to console on execution. This ruins the image. I don't understand what I'm doing wrong, so I've posted the code below in the hopes that someone will take a moment to show me the right way. Please?
I've removed the quotes to prevent more clutter. </p>
<pre><code>echo -en "\E[31m"
echo
echo _,.
echo ,` -.)
echo '( _/'-\\-.
echo /,|`--._,-^| ,
echo \_| |`-._/|| ,'|
echo | `-, / | / /
echo | || | / /
echo `r-._||/ __ / /
echo __,-<_ )`-/ `./ /
echo ' \ `---' \ / /
echo | |./ /
echo / // /
echo \_/' \ |/ /
echo | | _,^-'/ /
echo | , `` (\/ /_
echo \,.->._ \X-=/^
echo ( / `-._//^`
echo `Y-.____(__}
echo | {__)
echo ()`
</code></pre> | 25,214,148 | 2 | 1 | null | 2014-08-09 00:32:07.713 UTC | 10 | 2022-02-17 23:24:30.8 UTC | 2014-08-09 00:40:21.987 UTC | null | 1,899,640 | null | 3,698,316 | null | 1 | 27 | bash|scripting|syntax-error|ascii | 30,828 | <p>Quotes in bash are important syntactic elements, not clutter. However, to print ASCII art, save yourself the trouble of proper quoting and escaping and just use a <code>here document</code>:</p>
<pre><code>cat << "EOF"
_,.
,` -.)
'( _/'-\\-.
/,|`--._,-^| ,
\_| |`-._/|| ,'|
| `-, / | / /
| || | / /
`r-._||/ __ / /
__,-<_ )`-/ `./ /
' \ `---' \ / /
| |./ /
/ // /
\_/' \ |/ /
| | _,^-'/ /
| , `` (\/ /_
\,.->._ \X-=/^
( / `-._//^`
`Y-.____(__}
| {__)
()`
EOF
</code></pre>
<p>Make sure not to remove the quotes here. They are not optional. </p> |
33,301,069 | Difference between val.length and val().length in jQuery? | <p>What is difference between <code>$("#id").val.length</code> and <code>$("#id").val().length</code>?</p>
<p>When I write <code>$("#id").val.length</code> then the output is <code>1</code> and <code>$("#id").val().length</code> then the output is the length of the written characters.</p>
<p>What is the explanation?</p> | 33,301,107 | 3 | 2 | null | 2015-10-23 11:18:32.78 UTC | 2 | 2015-11-11 05:36:26.457 UTC | 2015-10-23 19:38:22.003 UTC | null | 63,550 | null | 5,060,008 | null | 1 | 29 | javascript|jquery | 33,675 | <p><code>$("#id").val</code> returns the function definition of <code>val</code> and <a href="http://ecma-international.org/ecma-262/6.0/#sec-function-instances-length"><strong><code>length</code> of a function is the number of parameters the function is expecting</strong></a> as the <code>val</code> takes one parameter(<strong>setter</strong> to set the value) the length is 1, whereas <code>val()</code> will invoke the function and get the returned value and <code>length</code> on it will return the number of characters in the value.</p>
<p>The correct use is <code>$(selector).val().length</code></p>
<p>I will also recommend to use VanillaJS's <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim">trim</a> or jQuery's <a href="https://api.jquery.com/jQuery.trim/">$.trim</a> on <code>val()</code> before checking <code>length</code> to remove leading and trailing spaces.</p> |
9,269,372 | Loop through all object properties at runtime | <p>I want to create an Objective-C base class that performs an operation on all properties (of varying types) at runtime. Since the names and types of the properties will not always be known, how can I do something like this?</p>
<pre><code>@implementation SomeBaseClass
- (NSString *)checkAllProperties
{
for (property in properties) {
// Perform a check on the property
}
}
</code></pre>
<p><strong>EDIT:</strong> This would be particularly useful in a custom <code>- (NSString *)description:</code> override.</p> | 9,269,544 | 3 | 0 | null | 2012-02-13 23:05:17.247 UTC | 9 | 2018-11-29 22:22:16.43 UTC | 2012-02-13 23:48:58.647 UTC | null | 205,926 | null | 205,926 | null | 1 | 9 | iphone|objective-c|ios|cocoa-touch | 10,615 | <p>To expand on mvds' answer (started writing this before I saw his), here's a little sample program that uses the Objective-C runtime API to loop through and print information about each property in a class:</p>
<pre><code>#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface TestClass : NSObject
@property (nonatomic, retain) NSString *firstName;
@property (nonatomic, retain) NSString *lastName;
@property (nonatomic) NSInteger *age;
@end
@implementation TestClass
@synthesize firstName;
@synthesize lastName;
@synthesize age;
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
unsigned int numberOfProperties = 0;
objc_property_t *propertyArray = class_copyPropertyList([TestClass class], &numberOfProperties);
for (NSUInteger i = 0; i < numberOfProperties; i++)
{
objc_property_t property = propertyArray[i];
NSString *name = [[NSString alloc] initWithUTF8String:property_getName(property)];
NSString *attributesString = [[NSString alloc] initWithUTF8String:property_getAttributes(property)];
NSLog(@"Property %@ attributes: %@", name, attributesString);
}
free(propertyArray);
}
}
</code></pre>
<p>Output:</p>
<blockquote>
<p>Property age attributes: T^q,Vage<br>
Property lastName attributes: T@"NSString",&,N,VlastName<br>
Property firstName attributes: T@"NSString",&,N,VfirstName </p>
</blockquote>
<p>Note that this program needs to be compiled with ARC turned on.</p> |
9,276,040 | How to search a string in another string? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/687577/how-to-see-if-a-substring-exists-inside-another-string-in-java-1-4">How to see if a substring exists inside another string in Java 1.4</a> </p>
</blockquote>
<p>How would I search for a string in another string?</p>
<p>This is an example of what I'm talking about:</p>
<pre><code>String word = "cat";
String text = "The cat is on the table";
Boolean found;
found = findInString(word, text); //this method is what I want to know
</code></pre>
<p>If the string "word" is in the string "text", the method "findInString(String, String)" returns true else it returns false.</p> | 9,276,067 | 5 | 0 | null | 2012-02-14 11:28:18.08 UTC | 5 | 2012-02-14 11:34:23.99 UTC | 2017-05-23 12:34:36.1 UTC | null | -1 | null | 1,208,733 | null | 1 | 29 | java|string | 189,014 | <p>That is already in the String class:</p>
<pre><code>String word = "cat";
String text = "The cat is on the table";
Boolean found;
found = text.contains(word);
</code></pre> |
9,092,445 | How do you remove numbering from headers when exporting from org-mode? | <p>The basic org-mode headers </p>
<pre><code>* Heading
** Sub-heading
* Another Heading
</code></pre>
<p>get converted to html like this</p>
<ol>
<li><p>Heading</p>
<p>1.2 Sub-heading</p></li>
<li><p>Another Heading</p></li>
</ol>
<p>(but imagine them larger and in h1 h2 fonts and sizes). How do you turn this off so that the headings are not numbered in the output html?</p> | 9,096,734 | 2 | 0 | null | 2012-02-01 07:43:40.75 UTC | 9 | 2017-07-20 22:49:26.33 UTC | 2015-02-05 17:11:25.063 UTC | null | 215,924 | null | 402,616 | null | 1 | 50 | emacs|org-mode | 18,470 | <p>Oleg's answer allows you to disable section numbering for all exports at all times. However if you only want to disable numbering on export for a single file you can use the following:</p>
<pre><code>#+OPTIONS: num:nil
</code></pre>
<p>If you want to limit it to only a certain depth you can replace nil with an integer specifying up to which headline you want the numbers to appear. For example <code>#+options: num:1</code> would turn your sample into:</p>
<pre><code>1. Heading
Sub-Heading
2. Another Heading
</code></pre>
<p>See <a href="http://orgmode.org/manual/Export-settings.html#Export-settings" rel="noreferrer">Export Setting</a> for the details and other export options that can be set on a per-file basis.<br>
See <a href="http://orgmode.org/manual/HTML-Specific-export-settings.html#HTML-Specific-export-settings" rel="noreferrer">HTML Specific Settings</a> for HTML specific ones.</p> |
9,131,191 | How do you query DynamoDB? | <p>I'm looking at Amazon's DynamoDB as it looks like it takes away all of the hassle of maintaining and scaling your database server. I'm currently using MySQL, and maintaining and scaling the database is a complete headache.</p>
<p>I've gone through the documentation and I'm having a hard time trying to wrap my head around how you would structure your data so it could be easily retrieved.</p>
<p>I'm totally new to NoSQL and non-relational databases.</p>
<p>From the Dynamo documentation it sounds like you can only query a table on the primary hash key, and the primary range key with a limited number of comparison operators. </p>
<p>Or you can run a full table scan and apply a filter to it. The catch is that it will only scan 1Mb at a time, so you'd likely have to repeat your scan to find X number of results.</p>
<p>I realize these limitations allow them to provide predictable performance, but it seems like it makes it really difficult to get your data out. And performing full table scans <em>seems</em> like it would be really inefficient, and would only become less efficient over time as your table grows.</p>
<p>For Instance, say I have a Flickr clone. My Images table might look something like:</p>
<ul>
<li>Image ID (Number, Primary Hash Key)</li>
<li>Date Added (Number, Primary Range Key)</li>
<li>User ID (String)</li>
<li>Tags (String Set)</li>
<li>etc</li>
</ul>
<p>So using query I would be able to list all images from the last 7 days and limit it to X number of results pretty easily.</p>
<p>But if I wanted to list all images from a particular user I would need to do a full table scan and filter by username. Same would go for tags.</p>
<p>And because you can only scan 1Mb at a time you may need to do multiple scans to find X number of images. I also don't see a way to easily stop at X number of images. If you're trying to grab 30 images, your first scan might find 5, and your second may find 40. </p>
<p>Do I have this right? Is it basically a trade-off? You get really fast predictable database performance that is virtually maintenance free. But the trade-off is that you need to build way more logic to deal with the results?</p>
<p>Or am I totally off base here?</p> | 9,136,507 | 3 | 0 | null | 2012-02-03 15:34:29.427 UTC | 15 | 2017-10-12 19:40:51.26 UTC | 2017-10-12 19:40:51.26 UTC | null | 3,885,376 | null | 673,269 | null | 1 | 55 | database|nosql|amazon-dynamodb | 24,621 | <p>Yes, you are correct about the trade-off between performance and query flexibility. </p>
<p>But there are a few tricks to reduce the pain - secondary indexes/denormalising probably being the most important. </p>
<p>You would have another table keyed on user ID, listing all their images, for example. When you add an image, you update this table as well as adding a row to the table keyed on image ID.</p>
<p>You have to decide what queries you need, then design the data model around them.</p> |
52,343,006 | How to print a part of a vue component without losing the style | <p>I want to print some content from a vue component. For example from the following snippet, I would like to print the <code>v-card-text</code> element which also has an id of <code>#print</code>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>new Vue({
el: '#app',
data() {
return {
dialog: false
}
},
methods: {
print() {
var prtContent = document.getElementById("print");
var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
}
})</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/vuetify/1.2.0/vuetify.min.css" />
</head>
<body>
<div id="app">
<v-app id="inspire">
<v-layout row justify-center>
<v-dialog v-model="dialog" persistent max-width="290">
<v-btn slot="activator" color="primary" dark>Open Dialog</v-btn>
<v-card>
<v-card-title class="headline">Print This:</v-card-title>
<v-card-text id="print">Lorem ipsum dolor sit amet.</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn color="green darken-1" flat @click.native="print">Print</v-btn>
</v-card>
</v-dialog>
</v-layout>
</v-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuetify/1.2.0/vuetify.min.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>However,when I get prompted for the print, all the styles associated with it goes away. How can I print a vue component in such a way so that the components won't lose the associated styles?
I recommend to copy the snippet to your local machine for the best effect.</p> | 52,345,332 | 3 | 1 | null | 2018-09-15 08:24:46.287 UTC | 10 | 2022-03-14 02:07:33.107 UTC | null | null | null | null | 2,594,250 | null | 1 | 19 | javascript|vue.js|printing | 40,374 | <p>You need to copy over the styles from the original document. Try something like this:</p>
<pre class="lang-es6 prettyprint-override"><code>// Get HTML to print from element
const prtHtml = document.getElementById('print').innerHTML;
// Get all stylesheets HTML
let stylesHtml = '';
for (const node of [...document.querySelectorAll('link[rel="stylesheet"], style')]) {
stylesHtml += node.outerHTML;
}
// Open the print window
const WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(`<!DOCTYPE html>
<html>
<head>
${stylesHtml}
</head>
<body>
${prtHtml}
</body>
</html>`);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
</code></pre> |
30,169,915 | Bootstrap 3: Create list with text and image left aligned | <p>I'd like to create a layout like the one in the image</p>
<p><img src="https://i.stack.imgur.com/5kaj4.png" alt="enter image description here"></p>
<p><a href="https://i.stack.imgur.com/qaiex.png" rel="noreferrer">large version</a>. </p>
<p>What is the best and cleanest way create the layout in HTML and the cleanest way to call it in the CSS? for example, should I create a div for each icon? This what I have tried so far: cssdeck.com/labs/full/vqnsgldc</p> | 30,171,266 | 2 | 3 | null | 2015-05-11 14:10:46.003 UTC | 2 | 2015-07-01 22:20:54.377 UTC | 2015-05-11 19:12:52.693 UTC | null | 4,418,587 | null | 4,788,760 | null | 1 | 4 | html|css|twitter-bootstrap|layout|icons | 44,369 | <p>You should look into using <a href="http://getbootstrap.com/components/#media" rel="noreferrer">bootstrap media components</a> they offer: <code>Abstract object styles for building ... a left- or right-aligned image alongside textual content</code>. </p>
<p>Here's an example in <a href="http://jsfiddle.net/cq2shm4w/" rel="noreferrer">JSFiddle</a> to start you off:</p>
<pre><code><div class="container">
<div class="row">
<div class="col-md-6">
<div class="media">
<div class="media-left">
<a href="#">
<img class="media-object" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9InllcyI/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iNjQiIGhlaWdodD0iNjQiIHZpZXdCb3g9IjAgMCA2NCA2NCIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+PGRlZnMvPjxyZWN0IHdpZHRoPSI2NCIgaGVpZ2h0PSI2NCIgZmlsbD0iI0VFRUVFRSIvPjxnPjx0ZXh0IHg9IjEzLjQ2MDkzNzUiIHk9IjMyIiBzdHlsZT0iZmlsbDojQUFBQUFBO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1mYW1pbHk6QXJpYWwsIEhlbHZldGljYSwgT3BlbiBTYW5zLCBzYW5zLXNlcmlmLCBtb25vc3BhY2U7Zm9udC1zaXplOjEwcHQ7ZG9taW5hbnQtYmFzZWxpbmU6Y2VudHJhbCI+NjR4NjQ8L3RleHQ+PC9nPjwvc3ZnPg==" alt="...">
</a>
</div>
<div class="media-body">
<h4 class="media-heading">Media heading</h4>
Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis.
</div>
</div>
</div>
<div class="col-md-6">
<div class="media">
<div class="media-left">
<a href="#">
<img class="media-object" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9InllcyI/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iNjQiIGhlaWdodD0iNjQiIHZpZXdCb3g9IjAgMCA2NCA2NCIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+PGRlZnMvPjxyZWN0IHdpZHRoPSI2NCIgaGVpZ2h0PSI2NCIgZmlsbD0iI0VFRUVFRSIvPjxnPjx0ZXh0IHg9IjEzLjQ2MDkzNzUiIHk9IjMyIiBzdHlsZT0iZmlsbDojQUFBQUFBO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1mYW1pbHk6QXJpYWwsIEhlbHZldGljYSwgT3BlbiBTYW5zLCBzYW5zLXNlcmlmLCBtb25vc3BhY2U7Zm9udC1zaXplOjEwcHQ7ZG9taW5hbnQtYmFzZWxpbmU6Y2VudHJhbCI+NjR4NjQ8L3RleHQ+PC9nPjwvc3ZnPg==" alt="...">
</a>
</div>
<div class="media-body">
<h4 class="media-heading">Media heading</h4>
Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis.
</div>
</div>
</div>
</div>
</div>
</code></pre> |
34,226,400 | Find the index of the k smallest values of a numpy array | <p>In order to find the index of the smallest value, I can use <code>argmin</code>: </p>
<pre><code>import numpy as np
A = np.array([1, 7, 9, 2, 0.1, 17, 17, 1.5])
print A.argmin() # 4 because A[4] = 0.1
</code></pre>
<p></p>
But how can I find the indices of the <strong>k-smallest values</strong>?</p>
<p>I'm looking for something like:</p>
<pre><code>print A.argmin(numberofvalues=3)
# [4, 0, 7] because A[4] <= A[0] <= A[7] <= all other A[i]
</code></pre>
<p></p></p>
<p><em>Note: in my use case A has between ~ 10 000 and 100 000 values, and I'm interested for only the indices of the k=10 smallest values. k will never be > 10.</em></p> | 34,226,816 | 4 | 2 | null | 2015-12-11 14:59:17.4 UTC | 30 | 2019-12-23 10:21:15.413 UTC | 2018-04-17 08:58:59.25 UTC | null | 2,062,965 | null | 1,422,096 | null | 1 | 100 | python|numpy | 121,450 | <p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argpartition.html" rel="noreferrer"><code>np.argpartition</code></a>. It does not sort the entire array. It only guarantees that the <code>kth</code> element is in sorted position and all smaller elements will be moved before it. Thus the first <code>k</code> elements will be the k-smallest elements.</p>
<pre><code>import numpy as np
A = np.array([1, 7, 9, 2, 0.1, 17, 17, 1.5])
k = 3
idx = np.argpartition(A, k)
print(idx)
# [4 0 7 3 1 2 6 5]
</code></pre>
<p>This returns the k-smallest values. Note that these may not be in sorted order.</p>
<pre><code>print(A[idx[:k]])
# [ 0.1 1. 1.5]
</code></pre>
<hr>
<p>To obtain the k-largest values use</p>
<pre><code>idx = np.argpartition(A, -k)
# [4 0 7 3 1 2 6 5]
A[idx[-k:]]
# [ 9. 17. 17.]
</code></pre>
<p>WARNING: Do not (re)use <code>idx = np.argpartition(A, k); A[idx[-k:]]</code> to obtain the k-largest.
That won't always work. For example, these are NOT the 3 largest values in <code>x</code>:</p>
<pre><code>x = np.array([100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 0])
idx = np.argpartition(x, 3)
x[idx[-3:]]
array([ 70, 80, 100])
</code></pre>
<hr>
<p>Here is a comparison against <code>np.argsort</code>, which also works but just sorts the entire array to get the result.</p>
<pre><code>In [2]: x = np.random.randn(100000)
In [3]: %timeit idx0 = np.argsort(x)[:100]
100 loops, best of 3: 8.26 ms per loop
In [4]: %timeit idx1 = np.argpartition(x, 100)[:100]
1000 loops, best of 3: 721 µs per loop
In [5]: np.alltrue(np.sort(np.argsort(x)[:100]) == np.sort(np.argpartition(x, 100)[:100]))
Out[5]: True
</code></pre> |
10,616,554 | ObservableDictionary for c# | <p>I'm trying to use following implementation of the ObservableDictionary: <a href="http://blogs.microsoft.co.il/blogs/shimmy/archive/2010/12/26/observabledictionary-lt-tkey-tvalue-gt-c.aspx" rel="noreferrer">ObservableDictionary (C#)</a>.</p>
<p>When I'm using following code while binding the dictionary to a DataGrid:</p>
<pre><code>ObserveableDictionary<string,string> dd=new ObserveableDictionary<string,string>();
....
dd["aa"]="bb";
....
dd["aa"]="cc";
</code></pre>
<p>at <code>dd["aa"]="cc";</code> I'm getting following exception</p>
<pre><code>Index was out of range. Must be non-negative and less than the size of the
collection. Parameter name: index
</code></pre>
<p>This exception is thrown in <code>CollectionChanged(this, new NotifyCollectionChangedEventArgs(action, newItem, oldItem)</code> in the following method:</p>
<pre><code>private void OnCollectionChanged(NotifyCollectionChangedAction action, KeyValuePair<TKey, TValue> newItem, KeyValuePair<TKey, TValue> oldItem)
{
OnPropertyChanged();
if (CollectionChanged != null) CollectionChanged(this, new NotifyCollectionChangedEventArgs(action, newItem, oldItem));
}
</code></pre>
<p>The <code>index</code> param seems to correspond to <code>KeyValuePair<TKey, TValue> oldItem</code>.</p>
<p>How can <code>KeyValuePair<TKey, TValue></code> be out of range, and what should I do to make this work?</p> | 10,616,706 | 6 | 1 | null | 2012-05-16 10:20:55.123 UTC | 2 | 2022-08-19 10:23:06.29 UTC | 2016-06-23 16:36:07.71 UTC | null | 649,524 | null | 847,200 | null | 1 | 8 | c#|wpf|dictionary|binding|inotifypropertychanged | 39,273 | <p>Similar data structure, to bind to Dictionary type collection</p>
<p><a href="http://drwpf.com/blog/2007/09/16/can-i-bind-my-itemscontrol-to-a-dictionary/" rel="noreferrer">http://drwpf.com/blog/2007/09/16/can-i-bind-my-itemscontrol-to-a-dictionary/</a></p>
<p>It provides a new Data structure ObservableDictionary and fires <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.propertychanged.aspx" rel="noreferrer">PropertyChanged</a> in case of any change to underlying Dictionary.</p> |
10,422,574 | Can I remove transients in the wp_options table of my WordPress install? | <p>I have recently noticed that my <code>wp_options</code> table seems to be a bit large. It contains 1161 rows, and is about 2.1mb in size.</p>
<p>I have installed <a href="http://wordpress.org/extend/plugins/clean-options/">Clean Options</a>. It looks like development stopped on the plugin back in 2010, but it still did the job.</p>
<p>I now have a long list of potentially orphaned entries. Is there an easy way to go about sorting these, and figuring out which to remove and which to keep? Also, could this be responsible for causing performance issues with the website?</p>
<p>Thank you for reading, any ideas are welcomed!</p>
<p><strong>Update</strong>: The Clean Options plugin returned some transients in the list, which lead me to find out that there are several hundred transient files in the <code>wp_options</code> table. There are a whole bunch that look like: </p>
<ul>
<li><code>_site_transient_browser_5728a0f1503de54634b3716638...</code> </li>
<li><code>_site_transient_timeout_browser_03df11ec4fda7630a5...</code></li>
<li><code>_transient_feed_83dcaee0f69f63186d51bf9a4...</code></li>
<li><code>_transient_plugin_slugs</code></li>
<li><code>_transient_timeout_feed_83dcaee0f69f63186d51bf9a4b...</code></li>
</ul>
<p>and so on. Like I said, there are several hundred rows that take look like this. Is it safe to just dump them?</p>
<p>Thanks</p> | 11,995,022 | 3 | 1 | null | 2012-05-02 22:25:13.103 UTC | 28 | 2022-05-15 19:20:43.99 UTC | 2012-05-03 00:08:42.477 UTC | null | 353,632 | null | 353,632 | null | 1 | 68 | mysql|database|wordpress | 72,563 | <p>You can safetly dump them. Wordpress and some plugins will re-create transients as needed. A transient is more or less the stored value from a complex query. The results are saved as a transient so that the system doesn't have to perform a common query over and over, instead it just looks for the transient if it exists and hasn't expired. Of course, make a backup of your database before making a change lest something goes wrong! </p>
<p>After backing everything up, you can run a mysql statement like this:</p>
<pre><code>DELETE FROM `wp_options` WHERE `option_name` LIKE ('%\_transient\_%')
</code></pre>
<p>[<strong>EDIT:</strong> statement fixed with escape characters, after comment suggestion]</p> |
22,753,785 | How to remove Ruby from Ubuntu | <p>I want to remove Ruby, so I try this. How can I remove this?</p>
<pre><code>sudo apt-get autoremove ruby
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package 'ruby' is not installed, so not removed
0 upgraded, 0 newly installed, 0 to remove and 534 not upgraded.
here@jaskaran:/$ whereis ruby
ruby: /usr/bin/ruby /usr/lib/ruby /usr/bin/X11/ruby /usr/share/man/man1/ruby.1.gz
here@jaskaran:/$ ruby -v
ruby 1.9.3p194 (2012-04-20 revision 35410) [i686-linux]
</code></pre> | 22,753,859 | 4 | 1 | null | 2014-03-31 04:44:48.213 UTC | 9 | 2018-01-23 11:01:36.993 UTC | 2014-03-31 05:08:07.037 UTC | null | 2,176,945 | null | 3,425,009 | null | 1 | 15 | ruby-on-rails|ruby | 48,045 | <p>Ubuntu...?</p>
<p>Use this to find out what executable you're running:</p>
<pre><code>$ which ruby
/usr/bin/ruby
</code></pre>
<p>Use this to find out what it actually is:</p>
<pre><code>$ readlink -f /usr/bin/ruby
/usr/bin/ruby1.8
</code></pre>
<p>Use this to find out what package it belongs to:</p>
<pre><code>$ dpkg -S /usr/bin/ruby1.8
ruby1.8: /usr/bin/ruby1.8
</code></pre>
<p>Use this to uninstall that:</p>
<pre><code>$ apt-get purge ruby1.8
</code></pre>
<blockquote>
<p><strong>Note</strong>: If you have installed Ruby using Version/Environment managers like <a href="https://rvm.io/" rel="noreferrer">RVM</a> or <a href="https://github.com/rbenv/rbenv" rel="noreferrer">Rbenv</a> then this method is not gonna work because Rubies will be installed as scripts not packages.</p>
</blockquote> |
7,249,440 | How to build debian package with CPack to execute setup.py? | <p>Until now, my project had only <strong>.cpp</strong> files that were compiled into different binaries and I managed to configure <strong>CPack</strong> to build a proper <strong>debian package</strong> without any problems.</p>
<p>Recently I wrote a couple of python applications and added them to the project, as well as some custom modules that I would also like to incorporate to the package. </p>
<p>After writing a <code>setup.py</code> script, I'm wondering how to add these files to the <strong>CPack</strong> configuration in a way that <code>setup.py</code> get's executed automatically when the user installs the package on the system with <code>dpkg -i package.deb</code>.</p>
<p>I'm struggling to find relevant information on how to configure CPack to install custom python applications/modules. Has anyone tried this?</p> | 7,918,913 | 2 | 2 | null | 2011-08-30 20:32:33.76 UTC | 10 | 2011-10-27 16:06:57.377 UTC | null | null | null | null | 176,769 | null | 1 | 15 | python|cmake|package|deb|cpack | 4,906 | <p>I figured out a way to do it but it's not very simple. I'll do my best to explain the procedure so please be patient.</p>
<h2>The idea of this approach is to use <em>postinst</em> and <em>prerm</em> to install and remove the python application from the system.</h2>
<p>In the <strong>CMakeLists.txt</strong> that defines the project, you need to state that <strong>CPACK</strong> is going to be used to generate a <strong>.deb package</strong>. There's some variables that need to be filled with info related to the package itself, but one named <code>CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA</code> is very important because it's used to specify the location of <strong>postinst</strong> and <strong>prerm</strong>, which are standard scripts of the <em>debian packaging system</em> that are automatically executed by <strong>dpkg</strong> when the package is installed/removed.</p>
<p>At some point of your <strong>main</strong> <code>CMakeLists.txt</code> you should have something like this:</p>
<pre><code>add_subdirectory(name_of_python_app)
set(CPACK_COMPONENTS_ALL_IN_ONE_PACKAGE 1)
set(CPACK_PACKAGE_NAME "fake-package")
set(CPACK_PACKAGE_VENDOR "ACME")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "fake-package - brought to you by ACME")
set(CPACK_PACKAGE_VERSION "1.0.2")
set(CPACK_PACKAGE_VERSION_MAJOR "1")
set(CPACK_PACKAGE_VERSION_MINOR "0")
set(CPACK_PACKAGE_VERSION_PATCH "2")
SET(CPACK_SYSTEM_NAME "i386")
set(CPACK_GENERATOR "DEB")
set(CPACK_DEBIAN_PACKAGE_MAINTAINER "ACME Technology")
set(CPACK_DEBIAN_PACKAGE_DEPENDS "libc6 (>= 2.3.1-6), libgcc1 (>= 1:3.4.2-12), python2.6, libboost-program-options1.40.0 (>= 1.40.0)")
set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA "${CMAKE_SOURCE_DIR}/name_of_python_app/postinst;${CMAKE_SOURCE_DIR}/name_of_python_app/prerm;")
set(CPACK_SET_DESTDIR "ON")
include(CPack)
</code></pre>
<p>Some of these variables are <strong>optional</strong>, but I'm filling them with info for educational purposes.</p>
<p>Now, let's take a look at the scripts:</p>
<p><strong>postinst</strong>:</p>
<pre><code>#!/bin/sh
# postinst script for fake_python_app
set -e
cd /usr/share/pyshared/fake_package
sudo python setup.py install
</code></pre>
<p><strong>prerm</strong>:</p>
<pre><code>#!/bin/sh
# prerm script
#
# Removes all files installed by: ./setup.py install
sudo rm -rf /usr/share/pyshared/fake_package
sudo rm /usr/local/bin/fake_python_app
</code></pre>
<p>If you noticed, script <strong>postinst</strong> enters at <code>/usr/share/pyshared/fake_package</code> and executes the <strong>setup.py</strong> that is laying there to install the app on the system. Where does this file come from and how it ends up there? This file is created by you and will be copied to that location when your package is installed on the system. This action is configured in <code>name_of_python_app/CMakeLists.txt</code>:</p>
<pre><code>install(FILES setup.py
DESTINATION "/usr/share/pyshared/fake_package"
)
install(FILES __init__.py
DESTINATION "/usr/share/pyshared/fake_package/fake_package"
)
install(FILES fake_python_app
DESTINATION "/usr/share/pyshared/fake_package/fake_package"
)
install(FILES fake_module_1.py
DESTINATION "/usr/share/pyshared/fake_package/fake_package"
)
install(FILES fake_module_2.py
DESTINATION "/usr/share/pyshared/fake_package/fake_package"
)
</code></pre>
<p>As you can probably tell, besides the python application I want to install there's also 2 custom python modules that I wrote that also need to be installed. Below I describe the contents of the most important files:</p>
<p><strong>setup.py</strong>:</p>
<pre><code>#!/usr/bin/env python
from distutils.core import setup
setup(name='fake_package',
version='1.0.5',
description='Python modules used by fake-package',
py_modules=['fake_package.fake_module_1', 'fake_package.fake_module_2'],
scripts=['fake_package/fake_python_app']
)
</code></pre>
<p><strong>_<em>init</em>_.py</strong>: is an empty file.</p>
<p><strong>fake_python_app</strong> : your python application that will be installed in /usr/local/bin</p>
<p>And that's pretty much it!</p> |
7,538,286 | How to embed a flash object on my website? | <p>Well, I must say this is embarrassing to ask, but to my defense I'll say that throughout my years of web development I've never encountered a case where embedding flash was absolutely necessary.</p>
<h2>The Question</h2>
<ul>
<li>Simple, how do I embed a flash object of any kind (*.swf or if there any other options, them too) to my website?</li>
</ul>
<h2>Some Points</h2>
<ul>
<li>I don't need the code, I already have that, I just don't really understand it.</li>
<li>I'm looking for a good explanation on how to use the <code><embed></code> or <code><object></code> elements.</li>
<li>I've been searching around but couldn't find a clear explanation, even in the specs.</li>
</ul>
<p>I'd award any good answer with an upvote, a cookie, and an accepted answer to the best :)</p> | 7,539,447 | 2 | 2 | null | 2011-09-24 09:59:18.453 UTC | 3 | 2018-02-08 15:23:04.747 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 871,050 | null | 1 | 15 | html|flash|embed | 57,854 | <p>Definitions:</p>
<p><a href="http://www.w3.org/wiki/HTML/Elements/embed">http://www.w3.org/wiki/HTML/Elements/embed</a></p>
<p><a href="http://www.w3.org/wiki/HTML/Elements/object">http://www.w3.org/wiki/HTML/Elements/object</a></p>
<p>Explanation on how to embed a flash object from Adobe:</p>
<p><a href="http://kb2.adobe.com/cps/415/tn_4150.html">http://kb2.adobe.com/cps/415/tn_4150.html</a></p>
<p>"The HTML OBJECT tag directs the browser to load Adobe Flash Player and then use it to play your SWF file."</p> |
3,379,207 | cmake, print compile/link commands | <p>Can somebody please enlighten me as to what the command line flag to CMake might be that will make it print out all the compile/link commands it executes?</p>
<p>I can't find this anywhere in the documentation. Many hours of my life have just evaporated. I'd just like to verify it's doing what I think it is, (then banish the infernal build system altogether and replace it with a GNU Makefile).
Thank you!</p> | 3,379,246 | 1 | 1 | null | 2010-07-31 17:51:52.393 UTC | 8 | 2021-08-13 02:34:34.49 UTC | null | null | null | null | 203,500 | null | 1 | 65 | makefile|cmake | 45,144 | <p>The <a href="http://sidvind.com/wiki/CMake/Verbose_output" rel="noreferrer">verbose argument</a> should do what you want.</p>
<p>Content copied (with format adjusted slightly) here for future reference:</p>
<blockquote>
<p>CMake/Verbose output</p>
<p>CMake has a nice colored output which hides the commandline. This is pretty to look at in the long run but sometimes when you write your configurations you want to know if you got all the compiler flags right. There is two ways to disable the pretty output, well, it's essentialy the same but still two different ways.</p>
<p>The first way is to simply run make with the additional argument "VERBOSE=1". This will show each command being run for this session, which is the most useful way to see if the flags is correct:</p>
<p>make VERBOSE=1</p>
<p>The second way is to permanently disable the pretty output in your CMakeLists.txt by setting CMAKE_VERBOSE_MAKEFILE:</p>
<p>set( CMAKE_VERBOSE_MAKEFILE on )</p>
<p>Content is available under <a href="https://creativecommons.org/licenses/by-sa/2.5/" rel="noreferrer">Attribution-ShareAlike 2.5</a> unless otherwise noted.</p>
</blockquote> |
21,388,845 | ggplot: arranging boxplots of multiple y-variables for each group of a continuous x | <p>I would like to create boxplots of multiple variables for groups of a continuous x-variable. The boxplots should be arranged next to each other for each group of x.</p>
<p>The data looks like this:</p>
<pre><code>require (ggplot2)
require (plyr)
library(reshape2)
set.seed(1234)
x <- rnorm(100)
y.1 <- rnorm(100)
y.2 <- rnorm(100)
y.3 <- rnorm(100)
y.4 <- rnorm(100)
df <- as.data.frame(cbind(x,y.1,y.2,y.3,y.4))
</code></pre>
<p>which I then melted</p>
<pre><code>dfmelt <- melt(df, measure.vars=2:5)
</code></pre>
<p>The facet_wrap as shown in this solution (
<a href="https://stackoverflow.com/questions/10987193/multiple-plots-by-factor-in-ggplot-facets">Multiple plots by factor in ggplot (facets)</a>)
gives me out each variable in an individual plot, but I would like to have the boxplots of each variable next to each other for each bin of x in one diagram.</p>
<pre><code>ggplot(dfmelt, aes(value, x, group = round_any(x, 0.5), fill=variable))+
geom_boxplot() +
geom_jitter() +
facet_wrap(~variable)
</code></pre>
<p><a href="https://i.stack.imgur.com/kboVT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kboVT.png" alt="fig1"></a></p>
<p>This shows the y-variables next to each other but does not bin x.</p>
<pre><code>ggplot(dfmelt) +
geom_boxplot(aes(x=x,y=value,fill=variable))+
facet_grid(~variable)
</code></pre>
<p><a href="https://i.stack.imgur.com/JqjEh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/JqjEh.png" alt="fig2"></a></p>
<p>Now I would like to produce such a plot for each bin of x.</p>
<p>What has to be changed or added?</p> | 21,389,997 | 1 | 2 | null | 2014-01-27 18:35:56.093 UTC | 13 | 2018-03-07 15:06:05.9 UTC | 2018-03-07 15:06:05.9 UTC | null | 1,146,071 | null | 3,241,568 | null | 1 | 18 | r|ggplot2|boxplot|continuous|r-factor | 49,224 | <p>Not exactly sure what you're looking for. Is this close?</p>
<p><img src="https://i.stack.imgur.com/m0E19.png" alt="enter image description here"></p>
<pre><code>library(ggplot2)
library(plyr)
ggplot(dfmelt, aes(x=factor(round_any(x,0.5)), y=value,fill=variable))+
geom_boxplot()+
facet_grid(.~variable)+
labs(x="X (binned)")+
theme(axis.text.x=element_text(angle=-90, vjust=0.4,hjust=1))
</code></pre>
<p><strong>EDIT</strong> (response to OP's comment)</p>
<p>You can put the Y's next to each other in each bin by just taking out the <code>facet_grid(...)</code> call, but I don't recommend it.</p>
<pre><code>ggplot(dfmelt, aes(x=factor(round_any(x,0.5)), y=value, fill=variable))+
geom_boxplot()+
labs(x="X (binned)")+
theme(axis.text.x=element_text(angle=-90, vjust=0.4,hjust=1))
</code></pre>
<p><img src="https://i.stack.imgur.com/OAqyE.png" alt=""></p>
<p>If you have to do it this way, it's still clearer using facets:</p>
<pre><code>dfmelt$bin <- factor(round_any(dfmelt$x,0.5))
ggplot(dfmelt, aes(x=bin, y=value, fill=variable))+
geom_boxplot()+
facet_grid(.~bin, scales="free")+
labs(x="X (binned)")+
theme(axis.text.x=element_blank())
</code></pre>
<p><img src="https://i.stack.imgur.com/jEjxC.png" alt=""></p>
<p>Note the addition of a <code>bin</code> column to <code>dfmelt</code>. This is because using <code>factor(round_any(x,0.5))</code> in the <code>facet_grid(...)</code> formula doesn't work.</p> |
1,365,163 | Can not call web service with basic authentication using WCF | <p>I've been given a web service written in Java that I'm not able to make any changes to. It requires the user authenticate with basic authentication to access any of the methods. The suggested way to interact with this service in .NET is by using Visual Studio 2005 with WSE 3.0 installed.</p>
<p>This is an issue, since the project is already using Visual Studio 2008 (targeting .NET 2.0). I could do it in VS2005, however I do not want to tie the project to VS2005 or do it by creating an assembly in VS2005 and including that in the VS2008 solution (which basically ties the project to 2005 anyway for any future changes to the assembly). I think that either of these options would make things complicated for new developers by forcing them to install WSE 3.0 and keep the project from being able to use 2008 and features in .NET 3.5 in the future... ie, I truly believe using WCF is the way to go.</p>
<p>I've been looking into using WCF for this, however I'm unsure how to get the WCF service to understand that it needs to send the authentication headers along with each request. I'm getting 401 errors when I attempt to do anything with the web service.</p>
<p>This is what my code looks like:</p>
<pre><code>WebHttpBinding webBinding = new WebHttpBinding();
ChannelFactory<MyService> factory =
new ChannelFactory<MyService>(webBinding, new EndpointAddress("http://127.0.0.1:80/Service/Service/"));
factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
factory.Credentials.UserName.UserName = "username";
factory.Credentials.UserName.Password = "password";
MyService proxy = factory.CreateChannel();
proxy.postSubmission(_postSubmission);
</code></pre>
<p>This will run and throw the following exception:</p>
<blockquote>
<p><em>The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server
was 'Basic realm=realm'.</em></p>
</blockquote>
<p>And this has an inner exception of:</p>
<blockquote>
<p><em>The remote server returned an error: (401) Unauthorized.</em></p>
</blockquote>
<p>Any thoughts about what might be causing this issue would be greatly appreciated.</p> | 1,365,915 | 3 | 0 | null | 2009-09-01 23:32:26.523 UTC | 6 | 2013-10-16 15:22:07.723 UTC | 2012-12-04 15:31:18.233 UTC | null | 13,302 | null | 46,429 | null | 1 | 17 | wcf|web-services|.net-3.5|wcf-security | 53,281 | <p>First question: is this a SOAP or a REST based Java service you're trying to call? </p>
<p>Right now, with the "webHttpBinding", you're using a REST-based approach. If the Java service is a SOAP service, then you'd need to change your binding to be "basicHttpBinding" instead.</p>
<p><strong>IF</strong> it's a SOAP based service, you should try this:</p>
<pre><code>BasicHttpBinding binding = new BasicHttpBinding();
binding.SendTimeout = TimeSpan.FromSeconds(25);
binding.Security.Mode = BasicHttpSecurityMode.Transport;
binding.Security.Transport.ClientCredentialType =
HttpClientCredentialType.Basic;
EndpointAddress address = new EndpointAddress(your-url-here);
ChannelFactory<MyService> factory =
new ChannelFactory<MyService>(binding, address);
MyService proxy = factory.CreateChannel();
proxy.ClientCredentials.UserName.UserName = "username";
proxy.ClientCredentials.UserName.Password = "password";
</code></pre>
<p>I've used this with various web services and it works - most of the time. </p>
<p>If that doesn't work, you'll have to find out more about what that Java webservice expects and how to send that relevant info to it.</p>
<p>Marc</p> |
2,051,383 | Latex: Using Minted package - how do I make it wrap the text (linebreaks=true) | <p>Im using the <code>Pygments</code> for a lot of things, and I'd like to also use this in my latex report. I found the package <code>Minted</code> which interacts with Pygments, but some of the comments and some of the code overflows the right margin. I have used lstlistings' <code>breaklines=true</code> in the past, but I don't see a way to get that functionality using the Minted package, any ideas? </p>
<pre><code>
\documentclass[10pt]{article}
\usepackage{fancyvrb}
\usepackage{minted}
\begin{document}
\begin{minted}[mathescape,
linenos,
numbersep=5pt,
frame=single,
numbersep=5pt,
xleftmargin=0,
]{python}
class Run(BaseModel):
"""
Run: unique Tool and multiple Inputs
Status:
Running => jobs are pending or runing and not all jobs have been completed
Paused => workers querying for 'Running' Runs won't get this Run until we change status again
Done => all jobs have completed and have a result_status = 'Done'
Incomplete => No results (inputs) have been associated with the Run
"""
name = models.CharField(max_length = 150,
unique=True)
tool = models.ForeignKey('Tool')
tags = models.ManyToManyField(RunTag, related_name="model_set")
\end{minted}
\end{document}
</code></pre> | 2,171,495 | 3 | 0 | null | 2010-01-12 18:33:12.31 UTC | 3 | 2015-07-27 14:43:32.973 UTC | null | null | null | null | 205,682 | null | 1 | 36 | syntax|latex|pygments | 30,583 | <p><del>Unfortunately, there’s no solution within <code>minted</code> at the moment or for the foreseeable future, sorry. Implementing the <code>breaklines</code> feature is quite difficult. Using <code>listings</code> instead may be your best solution here.</del></p>
<p>Minted now has a <code>breaklines</code> option.</p> |
41,168,942 | How to input a NodeJS variable into an SQL query | <p>I want to write an SQL query that contains a NodeJS variable. When I do this, it gives me an error of 'undefined'.</p>
<p>I want the SQL query below to recognize the <code>flightNo</code> variable. How can a NodeJS variable be input into an SQL query? Does it need special characters around it like <code>$</code> or <code>?</code>.</p>
<pre><code>app.get("/arrivals/:flightNo?", cors(), function(req,res){
var flightNo = req.params.flightNo;
connection.query("SELECT * FROM arrivals WHERE flight = 'flightNo'", function(err, rows, fields) {
</code></pre> | 41,172,686 | 2 | 0 | null | 2016-12-15 16:28:23.893 UTC | 4 | 2020-05-19 16:06:21.84 UTC | 2017-10-27 04:25:19.167 UTC | null | 1,961,728 | null | 7,242,756 | null | 1 | 11 | sql|node.js|node-mysql | 40,026 | <p>You will need to put the <strong>value</strong> of the variable into the SQL statement.</p>
<p>This is no good:</p>
<pre><code>"SELECT * FROM arrivals WHERE flight = 'flightNo'"
</code></pre>
<p>This will work, but it is not safe from SQL injection attacks:</p>
<pre><code>"SELECT * FROM arrivals WHERE flight = '" + flightNo + "'"
</code></pre>
<p>To be safe from SQL injection, you can escape your value like this:</p>
<pre><code>"SELECT * FROM arrivals WHERE flight = '" + connection.escape(flightNo) + "'"
</code></pre>
<p>But the best way is with parameter substitution:</p>
<pre><code>app.get("/arrivals/:flightNo", cors(), function(req, res) {
var flightNo = req.params.flightNo;
var sql = "SELECT * FROM arrivals WHERE flight = ?";
connection.query(sql, flightNo, function(err, rows, fields) {
});
});
</code></pre>
<p>If you have multiple substitutions to make, use an array:</p>
<pre><code>app.get("/arrivals/:flightNo", cors(), function(req, res) {
var flightNo = req.params.flightNo;
var minSize = req.query.minSize;
var sql = "SELECT * FROM arrivals WHERE flight = ? AND size >= ?";
connection.query(sql, [ flightNo, minSize ], function(err, rows, fields) {
});
});
</code></pre> |
32,822,473 | How to Access Function variables in Another Function | <p>I have a small issue while calling multiple variables in python one function to another. Like I have to access the variable of xxx() variables in yyy(). Help me to do this.?</p>
<p><strong>Example :</strong></p>
<pre><code>def xxx():
a=10
b=15
c=20
def yyy():
xxx()
print a ### value a from xxx()
print b ### value b from xxx()
yyy()
</code></pre> | 32,822,523 | 6 | 0 | null | 2015-09-28 12:00:50.983 UTC | 6 | 2022-07-04 12:37:48.103 UTC | null | null | null | null | 5,192,233 | null | 1 | 7 | python | 37,999 | <p>Return them from your first function and accept them in your second function. Example -</p>
<pre><code>def xxx():
a=10
b=15
c=20
return a,b
def yyy():
a,b = xxx()
print a ### value a from xxx()
print b ### value b from xxx()
yyy()
</code></pre> |
23,069,370 | Format a date using the new date time API | <p>I was playing with the new date time API but when running this:</p>
<pre><code>public class Test {
public static void main(String[] args){
String dateFormatted = LocalDate.now()
.format(DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println(dateFormatted);
}
}
</code></pre>
<p>It throws:</p>
<pre><code>Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay
at java.time.LocalDate.get0(LocalDate.java:680)
at java.time.LocalDate.getLong(LocalDate.java:659)
at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
at java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2543)
at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2182)
at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1745)
at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1719)
at java.time.LocalDate.format(LocalDate.java:1685)
at Test.main(Test.java:23)
</code></pre>
<p>When looking at the source code of the LocalDate class, I see:</p>
<pre><code> private int get0(TemporalField field) {
switch ((ChronoField) field) {
case DAY_OF_WEEK: return getDayOfWeek().getValue();
case ALIGNED_DAY_OF_WEEK_IN_MONTH: return ((day - 1) % 7) + 1;
case ALIGNED_DAY_OF_WEEK_IN_YEAR: return ((getDayOfYear() - 1) % 7) + 1;
case DAY_OF_MONTH: return day;
case DAY_OF_YEAR: return getDayOfYear();
case EPOCH_DAY: throw new UnsupportedTemporalTypeException("Invalid field 'EpochDay' for get() method, use getLong() instead");
case ALIGNED_WEEK_OF_MONTH: return ((day - 1) / 7) + 1;
case ALIGNED_WEEK_OF_YEAR: return ((getDayOfYear() - 1) / 7) + 1;
case MONTH_OF_YEAR: return month;
case PROLEPTIC_MONTH: throw new UnsupportedTemporalTypeException("Invalid field 'ProlepticMonth' for get() method, use getLong() instead");
case YEAR_OF_ERA: return (year >= 1 ? year : 1 - year);
case YEAR: return year;
case ERA: return (year >= 1 ? 1 : 0);
}
throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
}
</code></pre>
<p>As it described in the doc:</p>
<blockquote>
<p>This method will create a formatter based on a simple pattern of
letters and symbols as described in the class documentation.</p>
</blockquote>
<p>And all these letters are <a href="http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#patterns">defined</a>. </p>
<p>So why <code>DateTimeFormatter.ofPattern</code> doesn't allow us to use some pattern letters? </p> | 23,069,408 | 4 | 0 | null | 2014-04-14 20:08:30.26 UTC | 8 | 2022-04-12 15:38:17.83 UTC | 2014-10-19 21:43:06.313 UTC | null | 38,896 | null | 2,336,315 | null | 1 | 160 | java|datetime|java-8|java-time | 106,821 | <p><code>LocalDate</code> represents just a date, not a DateTime. So "HH:mm:ss" make no sense when formatting a <code>LocalDate</code>. Use a <code>LocalDateTime</code> instead, assuming you want to represent both a date and time.</p> |
30,895,944 | How to make a field in a definition required for some operations and not others | <p>I'm writing my swagger definition in yaml. Say I have a definition that looks something like this.</p>
<pre><code>paths:
/payloads:
post:
summary: create a payload
...
parameters:
- in: body
name: payload
description: New payload
required: true
schema:
$ref: "#/definitions/payload"
put:
summary: update a payload
...
parameters:
- in: body
name: payload
description: Updated existing payload
required: true
schema:
$ref: "#/definitions/payload"
...
definitions:
payload:
properties:
id:
type: string
someProperty:
type: string
...
</code></pre>
<p>Is there a way that I can indicate that the id property of a payload is required for the PUT operation and is optional (or should not appear at all) for the POST operation?</p> | 30,899,321 | 3 | 0 | null | 2015-06-17 15:27:27.07 UTC | 2 | 2018-07-16 15:11:26.77 UTC | null | null | null | null | 1,976,643 | null | 1 | 29 | swagger|swagger-2.0|swagger-editor | 14,337 | <p>You would have to define the models separately.</p>
<p>However, you have options for the cases of exclusion and difference.</p>
<p>If you're looking to exclude, which is the easy case, create a model of with the excluded property, say <code>ModelA</code>. Then define <code>ModelB</code> as <code>ModelA</code> plus the additional property:</p>
<pre><code>ModelB:
allOf:
- $ref: "#/definitions/ModelA"
- type: object
properties:
id:
type: string
</code></pre>
<p>If you're looking to define the difference, follow the same method above, and exclude the <code>id</code> from <code>ModelA</code>. Then define <code>ModelB</code> and <code>ModelC</code> as extending <code>ModelA</code> and add the <code>id</code> property to them, each with its own restrictions. Mind you, JSON Schema can allow you to follow the original example above for some cases to "override" a definition. However, since it is not really overriding, and one needs to understand the concepts of JSON Schema better to not make simple mistakes, I'd recommend going this path for now.</p> |
2,030,624 | Dependency Injection simple implementation | <p>after reading <a href="https://stackoverflow.com/questions/1967548/best-way-to-access-global-objects-like-database-or-log-from-classes-and-scripts">this</a> question i wonder if someone can help me understand how to implement correctly Dependency Injection with these PHP Classes:</p>
<pre><code>class DBClass
{
private $mMysqli;
function __construct(mysqli $database)
{
$this->mMysqli=$database;
}
function __destruct()
{
$this->mMysqli->close();
}
public function listUsers()
{
$query='SELECT * FROM Utente;';
$resultset=$this->mMysqli->query($query);
while($row = $resultset->fetch_array(MYSQLI_ASSOC)) {
echo $row['username'];
echo $row['pwd'];
echo "<br />\n";
}
}
public function runQuery($query)
{
return $resultset=$this->mMysqli->query($query);
}
public function getConnection()
{
return $this->mMysqli;
}
}
</code></pre>
<p>Session class:</p>
<pre><code>class Session
{
private $_session;
public $maxTime;
private $database;
public function __construct(DBClass $database)
{
$this->database=$database;
$this->maxTime['access'] = time();
$this->maxTime['gc'] = get_cfg_var('session.gc_maxlifetime');
session_set_save_handler(array($this,'_open'),
array($this,'_close'),
array($this,'_read'),
array($this,'_write'),
array($this,'_destroy'),
array($this,'_clean')
);
register_shutdown_function('session_write_close');
session_start();
...
}
}
</code></pre>
<p>User Class (for details about the currently logged in user):</p>
<pre><code>class User
{
private $username;
private $role;
private $session;
function __construct($session)
{
$this->session=$session;
...
}
}
</code></pre>
<p>Externally:</p>
<pre><code>$connection=new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
$database=new DBClass($connection);
$session=new Session($database);
$user=new User($session);
</code></pre>
<p>Is this the proper way? </p> | 2,030,769 | 1 | 0 | null | 2010-01-08 20:48:01.107 UTC | 9 | 2012-12-24 22:07:16.313 UTC | 2017-05-23 11:52:26.003 UTC | null | -1 | null | 243,873 | null | 1 | 4 | php|oop|design-patterns | 1,896 | <p>Yes. You are now injecting the dependencies through the constructor which provides for less coupling. You can now more easily swap out these dependencies, e.g. when UnitTesting you can replace them with Mocks.</p>
<p>You have still some coupling though by using the concrete DBClass as a TypeHint instead of an <a href="http://www.php.net/manual/en/language.oop5.interfaces.php" rel="noreferrer">interface</a>. So when you would want to use a different DBClass, it would have to be named DBClass. You could achieve more loose coupling by <a href="http://www.artima.com/lejava/articles/designprinciples.html" rel="noreferrer">coding against an interface</a> that the concrete classes have to implement instead.</p>
<p>To create only single instances of a class (as asked in the comments), you could either use a Singleton (like Kevin Peno suggested) or a Factory to create and keep track of if the instance has been created yet. Or use a DI Service Container, which is similar to a Factory, yet not the same thing. It creates and manages objects for you.</p>
<p>The <a href="http://components.symfony-project.org/dependency-injection/" rel="noreferrer">Symfony Components library has a Dependency Injection Container</a> with excellent documentation and introduction to the topic on how to further enhance DI this with Service Containers. The containers can also be used to limit instances. Check it out.</p> |
21,556,437 | Disable OPCache temporarily | <p>I recently moved to PHP 5.4 and installed OPCache, it's very powerful!</p>
<p>How can I temporarily disable the cache?</p>
<p>I tried :</p>
<pre><code> ini_set('opcache.enable', 0);
</code></pre>
<p>But it has no effect.</p>
<p>Thanks</p> | 21,556,994 | 4 | 0 | null | 2014-02-04 15:24:49.627 UTC | 16 | 2022-01-20 12:12:51.127 UTC | 2015-10-19 23:37:01.343 UTC | null | 3,467,557 | null | 1,308,710 | null | 1 | 49 | php|opcache | 108,599 | <p>Once your script runs, it's too late to not cache the file. You need to set it outside PHP:</p>
<ul>
<li><p>If PHP runs as Apache module, use an <code>.htaccess</code> file:</p>
<pre><code>php_flag opcache.enable Off
</code></pre>
</li>
<li><p>If PHP runs as CGI/FastCGI, use a <code>.user.ini</code> file:</p>
<pre><code>opcache.enable=0
</code></pre>
</li>
</ul>
<p>In all cases, you can also use good old system-wide <code>php.ini</code> if you have access to it.</p> |
64,156,202 | Add dense layer on top of Huggingface BERT model | <p>I want to add a dense layer on top of the bare BERT Model transformer outputting raw hidden-states, and then fine tune the resulting model. Specifically, I am using <a href="https://huggingface.co/dbmdz/bert-base-italian-xxl-cased" rel="noreferrer">this</a> base model. This is what the model should do:</p>
<ol>
<li>Encode the sentence (a vector with 768 elements for each token of the sentence)</li>
<li>Keep only the first vector (related to the first token)</li>
<li>Add a dense layer on top of this vector, to get the desired transformation</li>
</ol>
<p>So far, I have successfully encoded the sentences:</p>
<pre><code>from sklearn.neural_network import MLPRegressor
import torch
from transformers import AutoModel, AutoTokenizer
# List of strings
sentences = [...]
# List of numbers
labels = [...]
tokenizer = AutoTokenizer.from_pretrained("dbmdz/bert-base-italian-xxl-cased")
model = AutoModel.from_pretrained("dbmdz/bert-base-italian-xxl-cased")
# 2D array, one line per sentence containing the embedding of the first token
encoded_sentences = torch.stack([model(**tokenizer(s, return_tensors='pt'))[0][0][0]
for s in sentences]).detach().numpy()
regr = MLPRegressor()
regr.fit(encoded_sentences, labels)
</code></pre>
<p>In this way I can train a neural network by feeding it with the encoded sentences. However, this approach clearly does not fine tune the base BERT model. Can anybody help me? How can I build a model (possibly in pytorch or using the Huggingface library) that can be entirely fine tuned?</p> | 64,156,912 | 3 | 0 | null | 2020-10-01 13:16:01.94 UTC | 13 | 2022-07-12 10:39:23.233 UTC | null | null | null | null | 5,296,106 | null | 1 | 18 | python|python-3.x|neural-network|pytorch|huggingface-transformers | 11,660 | <p>There are two ways to do it: Since you are looking to fine-tune the model for a downstream task similar to classification, you can directly use:</p>
<p><code>BertForSequenceClassification</code> class. Performs fine-tuning of logistic regression layer on the output dimension of 768.</p>
<p>Alternatively, you can define a custom module, that created a bert model based on the pre-trained weights and adds layers on top of it.</p>
<pre><code>from transformers import BertModel
class CustomBERTModel(nn.Module):
def __init__(self):
super(CustomBERTModel, self).__init__()
self.bert = BertModel.from_pretrained("dbmdz/bert-base-italian-xxl-cased")
### New layers:
self.linear1 = nn.Linear(768, 256)
self.linear2 = nn.Linear(256, 3) ## 3 is the number of classes in this example
def forward(self, ids, mask):
sequence_output, pooled_output = self.bert(
ids,
attention_mask=mask)
# sequence_output has the following shape: (batch_size, sequence_length, 768)
linear1_output = self.linear1(sequence_output[:,0,:].view(-1,768)) ## extract the 1st token's embeddings
linear2_output = self.linear2(linear2_output)
return linear2_output
tokenizer = AutoTokenizer.from_pretrained("dbmdz/bert-base-italian-xxl-cased")
model = CustomBERTModel() # You can pass the parameters if required to have more flexible model
model.to(torch.device("cpu")) ## can be gpu
criterion = nn.CrossEntropyLoss() ## If required define your own criterion
optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()))
for epoch in epochs:
for batch in data_loader: ## If you have a DataLoader() object to get the data.
data = batch[0]
targets = batch[1] ## assuming that data loader returns a tuple of data and its targets
optimizer.zero_grad()
encoding = tokenizer.batch_encode_plus(data, return_tensors='pt', padding=True, truncation=True,max_length=50, add_special_tokens = True)
outputs = model(input_ids, attention_mask=attention_mask)
outputs = F.log_softmax(outputs, dim=1)
input_ids = encoding['input_ids']
attention_mask = encoding['attention_mask']
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
</code></pre> |
14,342,186 | VBA Multidimensional Arrays | <p>Is there a way to do the following in VBA?</p>
<p>Initialize a multidimensional array and fill it with a series of numbers,</p>
<pre><code> 1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
</code></pre>
<p>Then remove some specific columns, for eg. columns 1, 2, 4. So that the end result is just the 3rd and 5th column.</p>
<p>Lastly how does one convert the final output to a normal one dimensional array.</p> | 14,342,574 | 3 | 1 | null | 2013-01-15 16:26:20.03 UTC | 2 | 2018-09-27 16:57:45.37 UTC | 2013-01-15 17:01:13.24 UTC | null | 1,370,425 | null | 1,592,397 | null | 1 | 0 | arrays|vba|excel|multidimensional-array|arraylist | 44,999 | <p>Assume that you have these columns in an Excel sheeet. If you only have these data in these columns you may simple delete the columns you need :D Then you will end up with 2 columsn you desire. Without knowing what you really need at the end this is the best blind guess..</p>
<p>e.g. your columns starts at B to F:</p>
<pre><code>Columns("B:B").Delete Shift:=xlToLeft
Columns("C:C").Delete Shift:=xlToLeft
Columns("D:D").Delete Shift:=xlToLeft
</code></pre>
<p>You can use the same logic to process the array. </p>
<ul>
<li>Transpose the array into the sheet. </li>
<li>Delete the columns. </li>
<li>Then transpose the left over two columns to array. </li>
</ul>
<p>But what will you do with the last two columns without putting it into the sheet? Very curious. So please confirm what you need, so anyone here can help you.</p>
<p>EDIT as per OP's comment:</p>
<p>You may take a look at this posts and articles which has manupulation of arrays in different ways:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/14302891/excel-clear-cells-based-on-contents-of-a-list-in-another-sheet/14325173#14325173">Excel clear cells based on contents of a list in another sheet</a></li>
<li><a href="https://www.google.com.sg/search?q=vba+arrays&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-a&channel=fflb" rel="nofollow noreferrer">VBA Arrays</a> </li>
</ul>
<p>Then in order to populate a 2D array for an example in VBA, check this out:</p>
<pre><code>Dim i As Integer, j As Integer
Dim array2D As Variant, newArray2D as Variant
'-- 0 indexed based array with 2 rows 3 columns
ReDim array2D(0 To 1, 0 To 2)
For i = LBound(array2D, 1) To UBound(array2D, 1)
For j = LBound(array2D, 1) To UBound(array2D, 1)
array2D(i, j) = i + j
Next j
Next i
'--to delete the fastest is to use the above logic (worksheet)
'-- here you don't need to declare/redimentioned the array
'-- as transpose will do it with a 1 indexed based array
newArray2D = WorksheetFunction.Transpose(Sheets(2).Range("B2:D").Value)
</code></pre> |
20,413,674 | Bootstrap table row hover | <p>How do I make the background change of a table row in <code>Bootstrap 3</code> on hover. The table class I am using right now is <code>table table-striped</code>. I tried to add a extra class to the <code><tr></code> tags within the table and made the css like this <code>.table-row:hover{background:black;}</code>. Now only the non-striped rows are working. Isn't there a class in bootstrap that will allow me to easily implement this? Or should I use <code>JQuery</code> to fix this? I really cannot figure this one out by myself.</p> | 20,413,745 | 1 | 0 | null | 2013-12-06 00:27:48.763 UTC | 8 | 2018-06-08 09:45:01.017 UTC | 2017-02-03 09:33:21.73 UTC | null | 4,370,109 | null | 2,315,022 | null | 1 | 71 | twitter-bootstrap|twitter-bootstrap-3|hover|row|css-tables | 96,322 | <p>You need to add the <code>table-hover</code> class to the <code><table/></code> element. Like this:</p>
<pre><code><table class="table table-striped table-hover">
<tbody>
<tr>
<td>Col 1</td>
<td>Col 2 </td>
</tr>
</tbody>
</table>
</code></pre>
<p>Source: <a href="http://getbootstrap.com/css/#tables" rel="noreferrer">Documentation</a></p> |
26,562,531 | Material Design: Nav Drawer Width | <p>According to <a href="http://www.google.com/design/spec/layout/structure.html#structure-side-nav-1">the Material Design specs</a> the Nav Drawer's width on mobile devices must be </p>
<blockquote>
<p>side nav width = screen width - app bar height</p>
</blockquote>
<p>How do we implement this on android?</p>
<p>I have two partial solutions. First is the hacky way: in the containing activity I put this code:</p>
<pre>
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR1) {
final Display display = getWindowManager().getDefaultDisplay();
final Point size = new Point();
display.getSize(size);
final ViewGroup.LayoutParams params = mDrawerFragment.getView().getLayoutParams();
params.width = size.x - getResources().getDimensionPixelSize(
R.dimen.abc_action_bar_default_height_material
);
mFragmentUserList.getView().setLayoutParams(params);
}</pre>
<p>This, however, causes a second layout cycle and doesn't work in gingerbread: it is not optimal. </p>
<p>The second solution involves adding a Space between the fragment and the drawerLayout. It however, displaces the shadow and the spot where the user can press to return to the main app. It also crashes when the "hamburguer" icon is pressed. Not optimal either.</p>
<p>Is there a better solution, preferably one that involves styles and xml?</p> | 32,439,823 | 6 | 0 | null | 2014-10-25 12:46:18.613 UTC | 16 | 2016-03-20 04:59:46.34 UTC | null | null | null | null | 742,188 | null | 1 | 35 | android|android-appcompat|material-design | 40,960 | <p>With the <a href="http://android-developers.blogspot.cz/2015/05/android-design-support-library.html">Android Design Support Library</a> it is now really simple to implement navigation drawer including correct sizing. Use the <a href="https://developer.android.com/reference/android/support/design/widget/NavigationView.html">NavigationView</a> and either use its ability to make drawer out of menu resource (example <a href="http://android-developers.blogspot.cz/2015/05/android-design-support-library.html">here</a>) or you can just wrap it around the view which you currenty use for showing your drawer list (e.g. ListView, RecyclerView). NavigationView will then take care of the drawer sizing for you.</p>
<p>Here's an example how I use the NavigationView wrapped around ListView:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/navdrawer_layout"
android:fitsSystemWindows="true">
<!-- Layout where content is shown -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<include android:id="@+id/toolbar"
layout="@layout/toolbar" />
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/toolbar" />
<!-- Toolbar shadow for pre-lollipop -->
<View style="@style/ToolbarDropshadow"
android:layout_width="match_parent"
android:layout_height="3dp"
android:layout_below="@id/toolbar" />
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start">
<ListView
android:id="@+id/navdrawer_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:dividerHeight="0dp"
android:divider="@null"/>
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
</code></pre>
<p>This way you can use NavigationViews sizing and still use your own drawer list. Though it is much easier to make the drawer list out of menu resource (example <a href="http://android-developers.blogspot.cz/2015/05/android-design-support-library.html">here</a>) you can't use custom views for the list items. </p> |
63,469,458 | What is the connection between laziness and purity? | <blockquote>
<p><a href="https://twitter.com/haskellhutt/status/1295688884790140928" rel="noreferrer">Laziness is what kept Haskell pure. If it had been strict, purity would soon go out the window.</a></p>
</blockquote>
<p>I fail to see the connection between the evaluation strategy of a language and its purity. Considering the reputation of the tweet's author I am most certainly overlooking something. Maybe someone can shed some light.</p> | 63,469,951 | 3 | 4 | null | 2020-08-18 13:15:15.9 UTC | 8 | 2020-08-18 17:22:28.727 UTC | 2020-08-18 16:11:42.603 UTC | null | 849,891 | null | 5,536,315 | null | 1 | 45 | haskell|functional-programming|lazy-evaluation|language-implementation|purity | 3,793 | <p>You're right, from a modern POV this doesn't really make sense. What <em>is</em> true is that lazy-by-default would make reasoning about side-effectful code a nightmare, so lazyness does require purity – but not the other way around.</p>
<p>What does require lazyness though is the way Haskell in versions 1.0–1.2, following its predecessor <a href="http://miranda.org.uk/" rel="noreferrer">Miranda</a>, emulated IO without monads. Short of any explicit notion of side-effect sequencing, the type of executable programs was</p>
<pre><code>main :: [Response] -> [Request]
</code></pre>
<p>which would, for a simple interactive program, work something like this: <code>main</code> would at first just ignore its input list. So thanks to lazyness, the values in that list wouldn't actually need to exist, at that point. In the meantime it would produce a first <code>Request</code> value, e.g. a terminal prompt for the user to type something. What was typed would then come back as a <code>Response</code> value, which only now actually needed to be evaluated, giving rise to a new <code>Request</code>, etc. etc..</p>
<p><a href="https://www.haskell.org/definition/haskell-report-1.0.ps.gz" rel="noreferrer">https://www.haskell.org/definition/haskell-report-1.0.ps.gz</a></p>
<p>In version 1.3 they then switched to the monadic-IO interface that we all know and love today, and at that point lazyness wasn't really necessary anymore. But before that, common wisdom was that the only way to interact with the real world without lazyness was to allow side-effectful functions, thus the statement that without lazyness, Haskell would just have gone down the same path as Lisp and ML before it.</p> |
48,151,128 | Difference between production and development build in ReactJS | <p>Recently I started learning react and I saw a tutorial where they used <code>Webpack</code> to create the production and development builds. But there was no explanation on what the difference between those two builds is and which one you have to use when. I searched the internet but didn't find anything that helped me. Does anyone have a tutorial or an explanation that I missed/didn't read?</p> | 48,151,529 | 2 | 0 | null | 2018-01-08 13:17:24.21 UTC | 8 | 2021-04-21 08:18:40.02 UTC | 2019-04-16 10:56:24.48 UTC | null | 8,511,820 | null | 8,511,820 | null | 1 | 43 | reactjs|webpack|webpack-dev-server | 38,731 | <p>The development build is used - as the name suggests - for development reasons. You have Source Maps, debugging and often times hot reloading ability in those builds.</p>
<p>The production build, on the other hand, runs in production mode which means this is the code running on your client's machine. The production build runs uglify and builds your source files into one or multiple minimized files. It also extracts CSS and images and of course any other sources you're loading with Webpack. There's also no hot reloading included. Source Maps might be included as separate files depending on your webpack <code>devtool</code> <a href="https://webpack.js.org/configuration/devtool/" rel="noreferrer">settings</a>.</p>
<p>What specifically separates production from development is dependent on your preferences and requirements, which means it pretty much depends on what you write in your Webpack configuration.</p>
<p>The <a href="https://webpack.js.org/guides/production/" rel="noreferrer">webpack-production documentation </a> is very straight-forward.
Also, the article <a href="https://medium.com/netscape/webpack-3-react-production-build-tips-d20507dba99a" rel="noreferrer">Webpack 3 + React — Production build tips</a> describes the process of creating production builds for React with Webpack pretty good.</p> |
42,614,172 | How to redirect from a view to another view In Django | <p>This is a view written for my posts app in Django. The problem is that after filling the update form and submitting it happens successfully. But it creates confusion for the user because the same HTML page is there and how can I redirect into the updated object?</p>
<pre><code>def post_update(request,id=None):
instance=get_object_or_404(Post,id=id)
if instance.created_user != request.user.username :
messages.success(request, "Post owned by another user, You are having read permission only")
return render(request,"my_blog/denied.html",{})
else :
form=PostForm(request.POST or None,request.FILES or None,instance=instance)
if form.is_valid():
instance=form.save(commit=False)
instance.save()
context={ "form":form,
"instance":instance }
return render(request,"my_blog/post_create.html",context)
</code></pre> | 42,614,265 | 4 | 0 | null | 2017-03-05 21:20:28.26 UTC | 1 | 2022-08-25 08:17:24.473 UTC | 2022-08-03 17:10:19.133 UTC | null | 8,172,439 | null | 7,235,557 | null | 1 | 14 | python|python-3.x|django|redirect|django-views | 40,847 | <p>You can use <code>redirect</code> from http shortcuts.</p>
<pre><code>from django.shortcuts import redirect
def my_view(request):
...
object = MyModel.objects.get(...)
return redirect(object) #or return redirect('/some/url/')
</code></pre>
<p>Here is the <a href="https://docs.djangoproject.com/en/1.10/topics/http/shortcuts/#django.shortcuts.redirect" rel="noreferrer">link</a> to official docs.</p> |
39,088,473 | PySpark dataframe convert unusual string format to Timestamp | <p>I am using PySpark through Spark 1.5.0.
I have an unusual String format in rows of a column for datetime values. It looks like this:</p>
<pre><code>Row[(datetime='2016_08_21 11_31_08')]
</code></pre>
<p>Is there a way to convert this unorthodox <code>yyyy_mm_dd hh_mm_dd</code> format into a Timestamp?
Something that can eventually come along the lines of</p>
<pre><code>df = df.withColumn("date_time",df.datetime.astype('Timestamp'))
</code></pre>
<p>I had thought that Spark SQL functions like <code>regexp_replace</code> could work, but of course I need to replace
<code>_</code> with <code>-</code> in the date half
and <code>_</code> with <code>:</code> in the time part.</p>
<p>I was thinking I could split the column in 2 using <code>substring</code> and count backward from the end of time. Then do the 'regexp_replace' separately, then concatenate. But this seems to many operations? Is there an easier way?</p> | 39,089,098 | 3 | 0 | null | 2016-08-22 20:47:06.14 UTC | 11 | 2021-03-30 05:35:00.58 UTC | 2021-02-21 20:18:00.563 UTC | null | 2,753,501 | null | 4,179,714 | null | 1 | 38 | apache-spark|dataframe|pyspark|apache-spark-sql|timestamp | 90,562 | <p><strong>Spark >= 2.2</strong></p>
<pre class="lang-py prettyprint-override"><code>from pyspark.sql.functions import to_timestamp
(sc
.parallelize([Row(dt='2016_08_21 11_31_08')])
.toDF()
.withColumn("parsed", to_timestamp("dt", "yyyy_MM_dd HH_mm_ss"))
.show(1, False))
## +-------------------+-------------------+
## |dt |parsed |
## +-------------------+-------------------+
## |2016_08_21 11_31_08|2016-08-21 11:31:08|
## +-------------------+-------------------+
</code></pre>
<p><strong>Spark < 2.2</strong></p>
<p>It is nothing that <code>unix_timestamp</code> cannot handle:</p>
<pre class="lang-py prettyprint-override"><code>from pyspark.sql import Row
from pyspark.sql.functions import unix_timestamp
(sc
.parallelize([Row(dt='2016_08_21 11_31_08')])
.toDF()
.withColumn("parsed", unix_timestamp("dt", "yyyy_MM_dd HH_mm_ss")
# For Spark <= 1.5
# See issues.apache.org/jira/browse/SPARK-11724
.cast("double")
.cast("timestamp"))
.show(1, False))
## +-------------------+---------------------+
## |dt |parsed |
## +-------------------+---------------------+
## |2016_08_21 11_31_08|2016-08-21 11:31:08.0|
## +-------------------+---------------------+
</code></pre>
<p>In both cases the format string should be compatible with Java <a href="https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer"><code>SimpleDateFormat</code></a>.</p> |
40,515,949 | Where are ini files on MacOsX Sierra? | <p>I've just bought new MacBook Pro. Take a look on what <code>php -i | grep ini</code> returns:</p>
<pre><code>prompt> php -i | grep ini
Configuration File (php.ini) Path => /etc
Scan this dir for additional .ini files => (none)
Additional .ini files parsed => (none)
user_ini.cache_ttl => 300 => 300
user_ini.filename => .user.ini => .user.ini
Supported handlers => ndbm cdb cdb_make inifile flatfile
init_command_executed_count => 0
init_command_failed_count => 0
com_init_db => 0
Classes => AppendIterator, ArrayIterator, ArrayObject, BadFunctionCallException, BadMethodCallException, CachingIterator, CallbackFilterIterator, DirectoryIterator, DomainException, EmptyIterator, FilesystemIterator, FilterIterator, GlobIterator, InfiniteIterator, InvalidArgumentException, IteratorIterator, LengthException, LimitIterator, LogicException, MultipleIterator, NoRewindIterator, OutOfBoundsException, OutOfRangeException, OverflowException, ParentIterator, RangeException, RecursiveArrayIterator, RecursiveCachingIterator, RecursiveCallbackFilterIterator, RecursiveDirectoryIterator, RecursiveFilterIterator, RecursiveIteratorIterator, RecursiveRegexIterator, RecursiveTreeIterator, RegexIterator, RuntimeException, SplDoublyLinkedList, SplFileInfo, SplFileObject, SplFixedArray, SplHeap, SplMinHeap, SplMaxHeap, SplObjectStorage, SplPriorityQueue, SplQueue, SplStack, SplTempFileObject, UnderflowException, UnexpectedValueException
open sourced by => Epinions.com
</code></pre>
<p>And this is what happens when I run <code>php --ini</code></p>
<pre><code>prompt> $ php --ini
Configuration File (php.ini) Path: /etc
Loaded Configuration File: (none)
Scan for additional .ini files in: (none)
Additional .ini files parsed: (none)
</code></pre>
<p>It seems there current php is not loading any php.ini file. Is it possible?</p> | 40,516,071 | 8 | 3 | null | 2016-11-09 21:01:10.677 UTC | 3 | 2019-10-04 16:19:31.427 UTC | 2019-03-27 06:23:59.757 UTC | null | 1,420,625 | null | 1,420,625 | null | 1 | 24 | php|macos-sierra | 50,590 | <p>Current versions of Mac OS X do not ship with a <code>php.ini</code>. PHP uses internal defaults for all settings.</p>
<p>There is a sample configuration file installed at <code>/etc/php.ini.default</code>. If you need to customize PHP settings, you can use that file as a template to create a configuration file at <code>/etc/php.ini</code>. PHP will read settings from that file if it's present.</p> |
62,347,539 | Type mismatch inferred type is () -> Unit but FlowCollector<Int> was expected | <p>When trying to collect from a Flow the type suddenly mismatches, and it was working and then started suddenly. </p>
<p>In my viewmodel: </p>
<pre><code>class MyViewModel: ViewModel() {
lateinit var river: Flow<Int>
fun doStuff() {
river = flow {
emit(1)
}.flowOn(Dispatchers.Default)
.catch {
emit(0)
}
}
}
</code></pre>
<p>Then in my activity I have the following:</p>
<pre><code>lifecycleScope.launch {
viewModel.river.collect { it ->
// this whole collect is what has the error.
}
}
</code></pre>
<p>But <code>collect</code> gives the error: <code>Type mismatch: inferred type is () -> Unit but FlowCollector<Int> was expected</code>.</p>
<p>How could this be happening?</p> | 62,347,613 | 3 | 0 | null | 2020-06-12 15:33:01.173 UTC | 2 | 2022-06-17 15:26:54.51 UTC | null | null | null | null | 964,887 | null | 1 | 37 | android|kotlin|kotlin-coroutines|kotlin-flow | 4,508 | <p>Probably, you are using <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/collect.html" rel="noreferrer">the direct <code>collect()</code> function on <code>Flow</code></a>.</p>
<p>For your syntax, you need to <code>import</code> <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/collect.html" rel="noreferrer">the <code>collect()</code> extension function</a>.</p>
<p>(and I <em>really</em> wish that they did not name these the same...)</p> |
8,895,091 | How can I set the message on an exception in Java? | <p>I want to set a custom exception message. However, I'm unsure of how to do this. Will I need to create a custom exception class or is there an easier way of doing this?</p> | 8,895,131 | 8 | 1 | null | 2012-01-17 13:05:49.393 UTC | 2 | 2022-06-07 17:09:11.2 UTC | 2020-09-01 00:48:11.337 UTC | null | 63,550 | user843337 | null | null | 1 | 20 | java|exception | 88,019 | <p>Well, if the API offers an exception that suits your needs (IllegalArgumentException for example), just use it and pass your message in the constructor.</p> |
62,366,211 | VSCode ModuleNotFoundError: No module named X | <p>I am trying to build a new package, however, when I try to run any of the files from inside VSCode or from terminal, I am coming across this error:</p>
<pre><code>ModuleNotFoundError: No module name 'x'
</code></pre>
<p>My current folder structure is as follows:</p>
<pre><code>package
|---module
|------__init__.py
|------calculations.py
|------miscfuncs.py
|---tests
|------__init__.py
|------test_calcs.py
|---setup.py
|---requirements.txt
</code></pre>
<p>However, when I run my tests (PyTest) through VSCode and using <code>import module.calculations as calc</code> or <code>from module.calculations import Class</code> in test_calcs.py, the tests work as expected - which is confusing me.</p>
<p>I know this is a commonly asked question, but I cannot fathom out a solution that will work here.</p>
<p>I have tried checking the working directory is in system path using the code below. The first item on the returned list of directories is the one I am working in.</p>
<pre><code>import sys
print(sys.path)
</code></pre>
<p>I have also used the following in the files to no avail:</p>
<pre><code>import module.calculations
import .module.calculations
from . import miscfuncs
</code></pre>
<p>When trying <code>import .module.calculations</code>, I get the following:</p>
<pre><code>ModuleNotFoundError: No module named '__main__.module'; '__main__' is not a package
</code></pre>
<p>When trying <code>from . import miscfuncs</code> in calculations.py, I get the following error:</p>
<pre><code>ImportError: cannot import name 'miscfuncs'
</code></pre>
<p>When working on a file within the module folder, I can use a relative import: <code>import calculations</code> and it works fine. This is fine for files within module, but not when I am working in test_calcs.py.</p>
<p>In my setup.py, I have a line for:</p>
<pre><code>packages=['module']
</code></pre>
<p>Happy to post more info if required or a link to my repo for the full code.</p>
<p><strong>EDIT</strong></p>
<p>Following remram's solution:</p>
<p>I have updated <code>launch.json</code> to include the <code>CWD</code> and <code>PYTHONPATH</code> variables.</p>
<p>The module name is still not recognised, however, IntelliSense within VSCode is picking up the functions within the imported file just fine.</p>
<pre><code>"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"cwd": "${workspaceFolder}",
"env": {"PYTHONPATH": "${cwd}"
}
}
]
</code></pre> | 62,366,609 | 5 | 2 | null | 2020-06-13 22:21:38.01 UTC | 4 | 2022-09-12 07:14:15.12 UTC | 2020-12-14 18:54:55.627 UTC | null | 8,951,763 | null | 8,440,356 | null | 1 | 10 | python|visual-studio-code | 42,393 | <p>Make sure you are running from the <code>package</code> folder (not from <code>package/module</code>) if you want <code>import module.calculations</code> to work. You can also set the <code>PYTHONPATH</code> environment variable to the path to the <code>package</code> folder.</p> |
222,752 | Sorting a tuple that contains tuples | <p>I have the following tuple, which contains tuples:</p>
<pre><code>MY_TUPLE = (
('A','Apple'),
('C','Carrot'),
('B','Banana'),
)
</code></pre>
<p>I'd like to sort this tuple based upon the <strong>second</strong> value contained in inner-tuples (i.e., sort Apple, Carrot, Banana rather than A, B, C).</p>
<p>Any thoughts?</p> | 222,762 | 4 | 0 | null | 2008-10-21 17:40:51.567 UTC | 11 | 2012-04-12 23:36:04.39 UTC | null | null | null | Huuuze | 10,040 | null | 1 | 12 | python|sorting|tuples | 12,541 | <pre><code>from operator import itemgetter
MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=itemgetter(1)))
</code></pre>
<p>or without <code>itemgetter</code>:</p>
<pre><code>MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=lambda item: item[1]))
</code></pre> |
1,190,018 | How do I run a java program from a different directory? | <p>I have a java program that I would like to be able to run from anywhere on my machine. I would like to run it from my Cygwin command prompt. I've made scripts to call the java program. I added the location of the java program to the classpath, and the scripts work when I run them from the java program's directory. However, when I try to run from any other directory, I get:</p>
<pre><code>java.lang.NoClassDefFoundError: commandprogram/CommandProgram
</code></pre>
<p>This is my script:</p>
<pre><code>#!/bin/sh
CWD=`dirname "$0"`
java -cp "$CWD/classes;$CWD/lib/AJarFile.jar" commandprogram/CommandProgram
</code></pre>
<p>Changing the java line to the following:</p>
<pre><code>java -cp "$CWD/classes;$CWD/classes/commandprogram;$CWD/lib/AJarFile.jar" CommandProgram
</code></pre>
<p>produces the same results.</p> | 1,190,245 | 4 | 4 | null | 2009-07-27 19:10:26.907 UTC | 6 | 2012-07-03 20:37:37.15 UTC | 2009-07-27 19:36:12.673 UTC | null | 140,377 | null | 140,377 | null | 1 | 20 | java|bash|scripting|cygwin | 45,657 | <p>After trying just about everything I could think of, I echoed out the command and saw that there was mixing of Cygwin paths and Windows paths. The solution was to change the script to:</p>
<pre><code>#!/bin/sh
CWD=`dirname "$0"`
CWD=`cygpath -w "$CWD"`
java -cp "$CWD/classes;$CWD/lib/AJarFile.jar" commandprogram/CommandProgram
</code></pre>
<p>Then CWD changed to "C:\Program Files\..." instead of "/cygdrive/c/Program\ Files/..."</p>
<p>I had previously encountered this problem and solved it with the <code>cygpath -w</code> solution, but then changed my script slightly and didn't notice that the path problem came back.</p> |
571,850 | Adding elements to python generators | <p>Is it possible to append elements to a python generator?</p>
<p>I'm currently trying to get all images from a set of disorganized folders and write them to a new directory. To get the files, I'm using os.walk() which returns a list of image files in a single directory. While I can make a generator out of this single list, I don't know how to combine all these lists into one single generator. Any help would be much appreciated.</p>
<p>Related:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li>
</ul> | 571,928 | 4 | 0 | null | 2009-02-21 01:11:36.413 UTC | 9 | 2020-08-21 13:05:10.26 UTC | 2017-05-23 11:45:58.913 UTC | J.F. Sebastian | -1 | Francisco | 69,177 | null | 1 | 27 | python|append|generator | 29,448 | <p>This should do it, where <code>directories</code> is your list of directories:</p>
<pre><code>import os
import itertools
generators = [os.walk(d) for d in directories]
for root, dirs, files in itertools.chain(*generators):
print root, dirs, files
</code></pre> |
577,463 | Finding how similar two strings are | <p>I'm looking for an algorithm that takes 2 strings and will give me back a "factor of similarity".</p>
<p>Basically, I will have an input that may be misspelled, have letters transposed, etc, and I have to find the closest match(es) in a list of possible values that I have.</p>
<p>This is not for searching in a database. I'll have an in-memory list of 500 or so strings to match against, all under 30 chars, so it can be relatively slow.</p>
<p>I know this exists, i've seen it before, but I can't remember its name.</p>
<hr>
<p>Edit: Thanks for pointing out Levenshtein and Hamming.
Now, which one should I implement? They basically measure different things, both of which can be used for what I want, but I'm not sure which one is more appropriate.</p>
<p>I've read up on the algorithms, Hamming seems obviously faster. Since neither will detect two characters being transposed (ie. Jordan and Jodran), which I believe will be a common mistake, which will be more accurate for what I want?
Can someone tell me a bit about the trade-offs?</p> | 577,551 | 4 | 1 | null | 2009-02-23 12:18:17.23 UTC | 22 | 2009-02-23 13:16:34.14 UTC | 2009-02-23 12:39:16.837 UTC | Nick Fortescue | 5,346 | Daniel Magliola | 3,314 | null | 1 | 38 | algorithm|string-matching | 16,863 | <p>Ok, so the standard algorithms are:</p>
<p>1) <a href="http://en.wikipedia.org/wiki/Hamming_distance" rel="noreferrer">Hamming distance</a>
Only good for strings of the same length, but very efficient. Basically it simply counts the number of distinct characters. Not useful for fuzzy searching of natural language text.</p>
<p>2) <a href="http://en.wikipedia.org/wiki/Levenshtein_distance" rel="noreferrer">Levenstein distance</a>.
The Levenstein distance measures distance in terms of the number of "operations" required to transform one string to another. These operations include insertion, deletion and substition. The standard approach of calculating the Levenstein distance is to use dynamic programming.</p>
<p>3) <a href="http://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance" rel="noreferrer">Generalized Levenstein/(Damerau–Levenshtein distance)</a>
This distance also takes into consideration transpositions of characters in a word, and is probably the edit distance most suited for fuzzy matching of manually-entered text. The algorithm to compute the distance is a bit more involved than the Levenstein distance (detecting transpositions is not easy). Most common implementations are a modification of the <a href="http://en.wikipedia.org/wiki/Bitap_algorithm" rel="noreferrer">bitap</a> algorithm (like grep). </p>
<p>In general you would probably want to consider an implementation of the third option implemented in some sort of nearest neighbour search based on a k-d tree</p> |
48,081,436 | How you convert a std::string_view to a const char*? | <p>Compiling with gcc-7.1 with the flag <code>-std=c++17</code>, the following program raises an error:</p>
<pre><code>#include <string_view>
void foo(const char* cstr) {}
void bar(std::string_view str){
foo(str);
}
</code></pre>
<p>The error message is</p>
<pre><code>In function 'void bar(std::string_view)':
error: cannot convert 'std::string_view {aka std::basic_string_view<char>}' to 'const char*' for argument '1' to 'void foo(const char*)'
foo(str);
</code></pre>
<p>I'm surprised there is no conversion to <code>const char*</code> because other libraries (abseil, bde), provide similar <code>string_view</code> classes which implicitly convert to <code>const char*</code>.</p> | 48,081,509 | 3 | 1 | null | 2018-01-03 16:34:15.77 UTC | 4 | 2022-01-06 16:31:32.713 UTC | 2018-01-03 16:35:42.083 UTC | null | 3,002,139 | null | 1,691,145 | null | 1 | 52 | c++|string|c++17|string-view | 56,413 | <p>A <code>std::string_view</code> doesn't provide a conversion to a <code>const char*</code> because <strong>it doesn't store a null-terminated string</strong>. It stores a pointer to the first element, and the length of the string, basically. That means that you cannot pass it to a function expecting a null-terminated string, like <code>foo</code> (how else are you going to get the size?) that expects a <code>const char*</code>, and so it was decided that it wasn't worth it.</p>
<p>If you know for sure that you have a null-terminated string in your view, you can use <a href="http://en.cppreference.com/w/cpp/string/basic_string_view/data" rel="noreferrer"><code>std::string_view::data</code></a>.</p>
<p>If you're not you should reconsider whether using a <code>std::string_view</code> in the first place is a good idea, since if you want a guaranteed null-terminated string <code>std::string</code> is what you want. For a one-liner you can use <code>std::string(object).data()</code> (<strong>note</strong>: the return value points to a <em>temporary</em> <code>std::string</code> instance that will get destroyed after the end of the expression!).</p> |
25,701,168 | At what nesting level should components read entities from Stores in Flux? | <p>I'm rewriting my app to use Flux and I have an issue with retrieving data from Stores. I have a lot of components, and they nest a lot. Some of them are large (<code>Article</code>), some are small and simple (<code>UserAvatar</code>, <code>UserLink</code>).</p>
<p>I've been struggling with where in component hierarchy I should read data from Stores.<br />
I tried two extreme approaches, neither of which I quite liked:</p>
<h2>All entity components read their own data</h2>
<p>Each component that needs some data from Store receives just entity ID and retrieves entity on its own.<br />
For example, <code>Article</code> is passed <code>articleId</code>, <code>UserAvatar</code> and <code>UserLink</code> are passed <code>userId</code>.</p>
<p>This approach has several significant downsides (discussed under code sample).</p>
<pre><code>var Article = React.createClass({
mixins: [createStoreMixin(ArticleStore)],
propTypes: {
articleId: PropTypes.number.isRequired
},
getStateFromStores() {
return {
article: ArticleStore.get(this.props.articleId);
}
},
render() {
var article = this.state.article,
userId = article.userId;
return (
<div>
<UserLink userId={userId}>
<UserAvatar userId={userId} />
</UserLink>
<h1>{article.title}</h1>
<p>{article.text}</p>
<p>Read more by <UserLink userId={userId} />.</p>
</div>
)
}
});
var UserAvatar = React.createClass({
mixins: [createStoreMixin(UserStore)],
propTypes: {
userId: PropTypes.number.isRequired
},
getStateFromStores() {
return {
user: UserStore.get(this.props.userId);
}
},
render() {
var user = this.state.user;
return (
<img src={user.thumbnailUrl} />
)
}
});
var UserLink = React.createClass({
mixins: [createStoreMixin(UserStore)],
propTypes: {
userId: PropTypes.number.isRequired
},
getStateFromStores() {
return {
user: UserStore.get(this.props.userId);
}
},
render() {
var user = this.state.user;
return (
<Link to='user' params={{ userId: this.props.userId }}>
{this.props.children || user.name}
</Link>
)
}
});
</code></pre>
<p>Downsides of this approach:</p>
<ul>
<li>It's frustrating to have 100s components potentially subscribing to Stores;</li>
<li>It's <strong>hard to keep track of how data is updated and in what order</strong> because each component retrieves its data independently;</li>
<li>Even though you might <em>already</em> have an entity in state, you are forced to pass its ID to children, who will retrieve it again (or else break the consistency).</li>
</ul>
<h2>All data is read once at the top level and passed down to components</h2>
<p>When I was tired of tracking down bugs, I tried to put all data retrieving at the top level. This, however, proved impossible because for some entities I have several levels of nesting.</p>
<p>For example:</p>
<ul>
<li>A <code>Category</code> contains <code>UserAvatar</code>s of people who contribute to that category;</li>
<li>An <code>Article</code> may have several <code>Category</code>s.</li>
</ul>
<p>Therefore if I wanted to retrieve all data from Stores at the level of an <code>Article</code>, I would need to:</p>
<ul>
<li>Retrieve article from <code>ArticleStore</code>;</li>
<li>Retrieve all article's categories from <code>CategoryStore</code>;</li>
<li>Separately retrieve each category's contributors from <code>UserStore</code>;</li>
<li>Somehow pass all that data down to components.</li>
</ul>
<p>Even more frustratingly, whenever I need a deeply nested entity, I would need to add code to each level of nesting to additionally pass it down.</p>
<h2>Summing Up</h2>
<p>Both approaches seem flawed. How do I solve this problem most elegantly?</p>
<p>My objectives:</p>
<ul>
<li><p>Stores shouldn't have an insane number of subscribers. It's stupid for each <code>UserLink</code> to listen to <code>UserStore</code> if parent components already do that.</p>
</li>
<li><p>If parent component has retrieved some object from store (e.g. <code>user</code>), I don't want any nested components to have to fetch it again. I should be able to pass it via props.</p>
</li>
<li><p>I shouldn't have to fetch all entities (including relationships) at the top level because it would complicate adding or removing relationships. I don't want to introduce new props at all nesting levels each time a nested entity gets a new relationship (e.g. category gets a <code>curator</code>).</p>
</li>
</ul> | 25,701,169 | 4 | 1 | null | 2014-09-06 14:16:10.96 UTC | 47 | 2017-08-15 16:24:49.74 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 458,193 | null | 1 | 89 | javascript|reactjs|reactjs-flux | 15,629 | <p>The approach at which I arrived is having each components receive its data (not IDs) as a prop. If some nested component needs a related entity, it's up to the parent component to retrieve it.</p>
<p>In our example, <code>Article</code> should have an <code>article</code> prop which is an object (presumably retrieved by <code>ArticleList</code> or <code>ArticlePage</code>).</p>
<p>Because <code>Article</code> also wants to render <code>UserLink</code> and <code>UserAvatar</code> for article's author, it will subscribe to <code>UserStore</code> and keep <code>author: UserStore.get(article.authorId)</code> in its state. It will then render <code>UserLink</code> and <code>UserAvatar</code> with this <code>this.state.author</code>. If they wish to pass it down further, they can. No child components will need to retrieve this user again.</p>
<p>To reiterate:</p>
<ul>
<li>No component ever receives ID as a prop; all components receive their respective objects.</li>
<li>If child components needs an entity, it's parent's responsibility to retrieve it and pass as a prop.</li>
</ul>
<p>This solves my problem quite nicely. Code example rewritten to use this approach:</p>
<pre><code>var Article = React.createClass({
mixins: [createStoreMixin(UserStore)],
propTypes: {
article: PropTypes.object.isRequired
},
getStateFromStores() {
return {
author: UserStore.get(this.props.article.authorId);
}
},
render() {
var article = this.props.article,
author = this.state.author;
return (
<div>
<UserLink user={author}>
<UserAvatar user={author} />
</UserLink>
<h1>{article.title}</h1>
<p>{article.text}</p>
<p>Read more by <UserLink user={author} />.</p>
</div>
)
}
});
var UserAvatar = React.createClass({
propTypes: {
user: PropTypes.object.isRequired
},
render() {
var user = this.props.user;
return (
<img src={user.thumbnailUrl} />
)
}
});
var UserLink = React.createClass({
propTypes: {
user: PropTypes.object.isRequired
},
render() {
var user = this.props.user;
return (
<Link to='user' params={{ userId: this.props.user.id }}>
{this.props.children || user.name}
</Link>
)
}
});
</code></pre>
<p>This keeps innermost components stupid but doesn't force us to complicate the hell out of top level components.</p> |
25,819,889 | How can I check if an input is a integer or String, etc.. in JAVA? | <p>I am wondering how I can check if a user's input is a certain primitive type (I mean integer, String, etc... I think it's called primitive type?). I want a user to input something, then I check if it's a String or not, and do a certain action accordingly. (JAVA)
I have seen some codes like this:</p>
<pre><code>if (input == (String)input) { (RANDOM STUFF HERE) }
</code></pre>
<p>or something like </p>
<pre><code>if input.equals((String) input)
</code></pre>
<p>And they don't work. I want to know how I can <b>Check for only a String?</b> (EDITED OUT)
I was wondering if there was a function that can do that? Thanks for the answers</p>
<p>EDIT: With the help of everyone I have created my fixed code that does what I want it to:</p>
<pre><code>package files;
import java.util.*;
public class CheckforSomething {
static Scanner inputofUser = new Scanner(System.in);
static Object userInput;
static Object classofInput;
public static void main(String[] args){
try{
System.out.print("Enter an integer, only an integer: ");
userInput = inputofUser.nextInt();
classofInput = userInput.getClass();
System.out.println(classofInput);
} catch(InputMismatchException e) {
System.out.println("Not an integer, crashing down");
}
}
}
</code></pre>
<p>No need for answers anymore, thanks!</p> | 25,820,257 | 8 | 1 | null | 2014-09-13 04:41:38.247 UTC | 3 | 2020-05-30 10:26:29.663 UTC | 2014-09-13 05:18:03.6 UTC | user4017662 | null | user4017662 | null | null | 1 | 3 | java | 60,474 | <p>Use <strong>instanceof</strong> to check type and typecast according to your type:</p>
<pre><code> public class A {
public static void main(String[]s){
show(5);
show("hello");
}
public static void show(Object obj){
if(obj instanceof Integer){
System.out.println((Integer)obj);
}else if(obj instanceof String){
System.out.println((String)obj);
}
}
}
</code></pre> |
25,446,225 | How to enable one button inside a disabled fieldset | <p>I want to disable all the elements inside Fieldset but enable few buttons inside it.
<a href="http://plnkr.co/edit/VPFFOKTznJT5MGnG32bY?p=preview">Demo:</a> </p>
<pre><code><fieldset ng-disabled="true">
<legend>Personalia:</legend>
Name: <input type="text"><br>
Email: <input type="text"><br>
Date of birth: <input type="text">
<input type="button" value="See More (Enable this!!) " ng-click="ButtonClicked1()" ng-disabled="false"/>
Somethingelse: <input type="text">
<input type="button" value="View Details " ng-click="ButtonClicked2()"/>
</fieldset>
</code></pre> | 25,448,337 | 3 | 2 | null | 2014-08-22 11:43:08.907 UTC | 2 | 2020-03-23 17:20:35.197 UTC | 2015-09-09 10:14:13.26 UTC | null | 1,329,934 | null | 3,640,976 | null | 1 | 35 | javascript|html|angularjs | 14,158 | <p>Try this:</p>
<h1><a href="http://jsfiddle.net/Jge9z/2042/" rel="nofollow">DEMO</a></h1>
<p>HTML:</p>
<pre><code><fieldset id="form">
<legend>Personalia:</legend>
Name: <input type="text" /><br />
Email: <input type="text" /><br />
Date of birth: <input type="text" />
<input id="btn1" type="button" value="See More (Enable this!!) " onclick="ButtonClicked1()" />
Somethingelse: <input type="text" />
<input type="button" value="View Details " onclick="ButtonClicked2()"/>
</fieldset>
</code></pre>
<p>SCRIPT:</p>
<pre><code>$('#form :input').prop('disabled', true);
$("#btn1").prop('disabled', false);
</code></pre> |
20,578,846 | Ignore missing properties during Jackson JSON deserialization in Java | <p>In the example</p>
<pre class="lang-java prettyprint-override"><code>class Person {
String name;
int age;
}
</code></pre>
<p>If the JSON object has a missing property 'age',</p>
<pre class="lang-json prettyprint-override"><code>{
"name": "John"
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>Person person = objectMapper.readValue(jsonFileReader, Person.class);
</code></pre>
<p>it throws a <code>JsonMappingException</code> saying it cannot deserialize. Is there an <em>annotation</em> to ignore missing fields during deserialization?</p> | 20,671,202 | 7 | 0 | null | 2013-12-14 01:56:13.567 UTC | 6 | 2022-04-08 03:59:02.53 UTC | 2021-11-06 12:15:12.657 UTC | null | 466,862 | null | 379,151 | null | 1 | 72 | java|json|serialization|jackson | 123,122 | <p>I think what you want is</p>
<pre><code>@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Person {
...
}
</code></pre>
<p>that's the Jackson 1.x way. I think there's a new way in 2.x. Something like</p>
<pre><code>@JsonInclude(Include.NON_NULL)
public class Person {
...
}
</code></pre>
<p>These will tell Jackson to only serialize values that are not null, and don't complain when deserializing a missing value. I think it will just set it to the Java default.</p> |
34,792,146 | Export to csv/excel from kibana | <p>I am building a proof of concept using Elasticsearch Logstash and Kibana for one of my projects. I have the dashboard with the graphs working without any issue. One of the requirements for my project is the ability to download the file(csv/excel).
In kibana the only option i saw for downloading the file is by clicking on edit button on the visualization created. Is it possible to add a link on the dashboard that would allow users to download the file without going into the edit mode. And secondly I would like to disable/hide the edit mode for anyone other than me who views the dashboard.
Thanks</p> | 34,798,953 | 4 | 2 | null | 2016-01-14 14:33:38.207 UTC | 13 | 2019-12-23 16:56:14.387 UTC | null | null | null | null | 147,306 | null | 1 | 64 | elasticsearch|logstash|export-to-csv|kibana-4 | 172,529 | <p>I totally missed the export button at the bottom of each visualization.
As for read only access...Shield from Elasticsearch might be worth exploring.</p> |
25,234,698 | SpriteKit Texture Atlas vs Image xcassets | <p>I am making a game and I noticed that during some scenes, my FPS kept dropping around the 55-60FPS area (using texture atlas). This drove me nuts so I decided to put all my assets to the Images.xcassets folder and voila, steady 60FPS.</p>
<p>I thought this was a fluke or that I was doing something wrong, so I decided to start a new project and perform some benchmarks...</p>
<hr>
<p>Apple's documentation says that using texture atlas's will improve app performance. Basically, allowing your app to take advantage of batch rendering. However... </p>
<p>The Test (<a href="https://github.com/JRam13/JSGlitch" rel="noreferrer">https://github.com/JRam13/JSGlitch</a>):</p>
<pre><code>- (void)runTest
{
SKAction *spawn = [SKAction runBlock:^{
for (int i=0; i<10; i++) {
SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:@"Spaceship"];
sprite.xScale = 0.5;
sprite.yScale = 0.5;
sprite.position = CGPointMake(0, [self randomNumberBetweenMin:0 andMax:768]);
SKAction *action = [SKAction rotateByAngle:M_PI duration:1];
[sprite runAction:[SKAction repeatActionForever:action]];
SKAction *move = [SKAction moveByX:1200 y:0 duration:2];
[sprite runAction:move];
//notice I don't remove from parent (see test2 below)
[self addChild:sprite];
}
}];
SKAction *wait = [SKAction waitForDuration:.1];
SKAction *sequence = [SKAction sequence:@[spawn,wait]];
SKAction *repeat = [SKAction repeatActionForever:sequence];
[self runAction:repeat];
}
</code></pre>
<p>Results:</p>
<p><img src="https://i.stack.imgur.com/IiI14.png" alt="enter image description here"></p>
<p>Tests repeatedly show that using the xcassets performed way better than the atlas counterpart in FPS. The atlas does seem to manage memory marginally better than the xcassets though.</p>
<p>Anybody know why these results show that images.xcassets has better performance than the atlas?</p>
<hr>
<p>Some hypotheses I've come up with:</p>
<ul>
<li>xcassets is just better optimized than atlasas.</li>
<li>atlasas are good at drawing lots of images in one draw pass, but have bigger overhead with repeated sprites. If true, this means that if your sprite appears multiple times on screen (which was the case in my original game), it is better to remove it from the atlas. </li>
<li><strike>atlas sheets must be filled in order to optimize performance</strike></li>
</ul>
<hr>
<p><strong>Update</strong></p>
<p>For this next test I went ahead and removed the sprite from parent after it goes offscreen. I also used 7 different images. We should see a huge performance gain using atlas due to the draw count but...</p>
<p><img src="https://i.stack.imgur.com/XqaG7.png" alt="enter image description here"></p> | 25,236,430 | 1 | 2 | null | 2014-08-11 01:34:23.23 UTC | 12 | 2018-02-21 16:10:53.707 UTC | 2014-08-11 21:41:23.343 UTC | null | 2,446,178 | null | 2,446,178 | null | 1 | 21 | ios|sprite-kit|performance-testing|xcasset|texture-atlas | 4,292 | <p>First, revise your test to match this :</p>
<pre><code> for (int i=0; i<10; i++) {
SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:@"Spaceship"];
sprite.xScale = 0.5;
sprite.yScale = 0.5;
float spawnY = arc4random() % 768;
sprite.position = CGPointMake(0, spawnY);
SKAction *action = [SKAction rotateByAngle:M_PI duration:1];
[sprite runAction:[SKAction repeatActionForever:action]];
SKAction *move = [SKAction moveByX:1200 y:0 duration:2];
// next three lines replace the runAction line for move
SKAction *remove = [SKAction removeFromParent];
SKAction *sequence = [SKAction sequence:@[move, remove]];
[sprite runAction:sequence];
[self addChild:sprite];
}
</code></pre>
<p>Rerun your tests and you should notice that your framerate NEVER deteriorates as in your tests. Your tests were basically illustrating what happens when you never remove nodes, but keep creating new ones.</p>
<p>Next, add the following line to your ViewController when you set up your skview :</p>
<pre><code>skView.showsDrawCount = YES;
</code></pre>
<p>This will allow you to see the draw count and properly understand where you are getting your performance boost with SKTextureAtlas.</p>
<p>Now, instead of having just one image , gather 3 images and modify your test by choosing a random one of those images each time it creates a node, you can do it something like this :</p>
<pre><code> NSArray *imageNames = @[@"image-0", @"image-1", @"image-2"];
NSString *imageName = imageNames[arc4random() % imageNames.count];
</code></pre>
<p>In your code, create your sprite with that imageName each time through the loop. ie :</p>
<pre><code>SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:imageName];
</code></pre>
<p>In your SKTextureAtlas test, use that same imageName obviously to create each sprite.</p>
<p>Now... rerun your tests and take note of the draw count in each test.</p>
<p>This should give you a tangible example of what batch rendering is about with SKTextureAtlas. </p>
<p>It's no about rendering the same sprite image thousands of times.</p>
<p>It's about drawing many different sprites images in the same draw pass. </p>
<p>There is likely some overhead in getting this rendering optimization, but I think the draw count should be self explanatory as to why that overhead is moot when all things are considered.</p>
<p>Now, you can hypothesize some more :)</p>
<p><strong>UPDATE</strong></p>
<p>As mentioned in the comments, my post was to expose why your test was not a good test for the benefits of SKTextureAtlas and was flawed if looking to analyze it in a meaningful way. Your test was like testing for measles with a mumps test. </p>
<p>Below is a github project that I put together to pinpoint where an SKTextureAtlas is appropriate and indeed superior to xcassets.</p>
<p><a href="https://github.com/proto-typical/atals-comparison">atlas-comparison</a></p>
<p>Just run the project on your device and then tap to toggle between tests. You can tell when it's testing with SKTextureAtlas because the draw count will be 1 and the framerate will be 60fps. </p>
<p>I isolated what will be optimized with a SKTextureAtlas. It's a 60 frame animation and 1600 nodes playing that animation. I offset their start frames so that they all aren't on the same frame at the same time. I also kept everything uniform for both tests, so that it's a direct comparison. </p>
<p>It's not accurate for someone to think that using SKTextureAtlas will just optimize all rendering. It's optimization comes by reducing draw count via batch rendering. So, if your framerate slowdown is not something that can be improved via batch rendering, SKTexture atlas is the wrong tool for the job. right ?</p>
<p>Similar to pooling of objects, where you can gain optimization via not creating and killing your game objects constantly, but instead reusing them from a pool of objects. However if you are not constantly creating and killing objects in your game, pooling ain't gonna optimize your game.</p>
<p>Based on what I saw you describe as your game's issue in the discussion log , pooling is probably the right tool for the job in your case.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.