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
49,808,950
Secure active storage with devise
<p>Using devise gem to authenticate all users of an application. I'm trying to implement Active Storage. </p> <p>Let's say that all users must be authenticated as soon as they reach the app: </p> <pre><code>class ApplicationController &lt; ActionController::Base before_action :authenticate_user! ... end </code></pre> <p>How to secure the Active Storage generated routes? </p> <p>URL of an uploaded file can be accessed without having to authenticate first. The unauthenticated user can get the file url generated by Active Storage.</p>
50,118,809
2
3
null
2018-04-13 03:39:07.37 UTC
9
2022-05-14 15:19:19.403 UTC
null
null
null
null
2,151,934
null
1
16
ruby-on-rails|rails-activestorage
5,603
<p>This is not a full answer but a starting point:</p> <p>The gist: You would need to override the redirect controller.</p> <p>The <a href="http://edgeapi.rubyonrails.org/classes/ActiveStorage/BlobsController.html" rel="nofollow noreferrer">docs for activestorage/app/controllers/active_storage/blobs_controller.rb</a> say:</p> <blockquote> <p>If you need to enforce access protection beyond the security-through-obscurity factor of the signed blob references, you'll need to implement your own authenticated redirection controller.</p> </blockquote> <p>Also if you plan to use previews the <a href="http://edgeapi.rubyonrails.org/classes/ActiveStorage/Blob/Representable.html#method-i-preview" rel="nofollow noreferrer">docs for activestorage/app/models/active_storage/blob/representable.rb</a> say</p> <blockquote> <p>Active Storage provides one [controller action for previews], but you may want to create your own (for example, if you need authentication).</p> </blockquote> <p>Also you might find some relevant information in <a href="https://github.com/rails/rails/issues/31419" rel="nofollow noreferrer">this rails github issue</a></p> <p><strong>Update:</strong> Here is a minimal example that &quot;should&quot; work for preventing unauthorised access to the redirects when using the <code>devise</code> gem.</p> <p>How the url, that the user will be redirected to if logged, is then secured is still another story I guess. By default they expire after 5 minutes but this could be set to a shorter period like 10 seconds (if you replace line 6 in example below with <code>expires_in 10.seconds</code>)</p> <p>Create a file <code>app/controllers/active_storage/blobs_controller.rb</code> with the following code:</p> <pre><code>class ActiveStorage::BlobsController &lt; ActiveStorage::BaseController before_action :authenticate_user! include ActiveStorage::SetBlob def show expires_in ActiveStorage::Blob.service.url_expires_in redirect_to @blob.service_url(disposition: params[:disposition]) end end </code></pre> <p>Please note that the only thing that changed from the <a href="https://github.com/rails/rails/blob/main/activestorage/app/controllers/active_storage/blobs/redirect_controller.rb" rel="nofollow noreferrer">original code</a> is that the second line is added</p> <pre><code>before_action :authenticate_user! </code></pre> <p><strong>Update 2:</strong></p> <p>Here is a concern that you can include in <code>ActiveStorage::RepresentationsController</code> and <code>ActiveStorage::BlobsController</code> to enable <code>devise</code> authentication for <code>ActiveStorage</code></p> <p>See gist is at <a href="https://gist.github.com/dommmel/4e41b204b97238e9aaf35939ae8e1666" rel="nofollow noreferrer">https://gist.github.com/dommmel/4e41b204b97238e9aaf35939ae8e1666</a> also included here:</p> <pre><code># Rails controller concern to enable Devise authentication for ActiveStorage. # Put it in +app/controllers/concerns/blob_authenticatable.rb+ and include it when overriding # +ActiveStorage::BlobsController+ and +ActiveStorage::RepresentationsController+. # # Optional configuration: # # Set the model that includes devise's database_authenticatable. # Defaults to Devise.default_scope which defaults to the first # devise role declared in your routes (usually :user) # # blob_authenticatable resource: :admin # # To specify how to determine if the current_user is allowed to access the # blob, override the can_access_blob? method # # Minimal example: # # class ActiveStorage::BlobsController &lt; ActiveStorage::BaseController # include ActiveStorage::SetBlob # include AdminOrUserAuthenticatable # # def show # expires_in ActiveStorage::Blob.service.url_expires_in # redirect_to @blob.service_url(disposition: params[:disposition]) # end # end # # Complete example: # # class ActiveStorage::RepresentationsController &lt; ActiveStorage::BaseController # include ActiveStorage::SetBlob # include AdminOrUserAuthenticatable # # blob_authenticatable resource: :admin # # def show # expires_in ActiveStorage::Blob.service.url_expires_in # redirect_to @blob.representation(params[:variation_key]).processed.service_url(disposition: params[:disposition]) # end # # private # # def can_access_blob?(current_user) # @blob.attachments.map(&amp;:record).all? { |record| record.user == current_user } # end # end module BlobAuthenticatable extend ActiveSupport::Concern included do around_action :wrap_in_authentication end module ClassMethods def auth_resource @auth_resource || Devise.default_scope end private def blob_authenticatable(resource:) @auth_resource = resource end end private def wrap_in_authentication is_signed_in_and_authorized = send(&quot;#{self.class.auth_resource}_signed_in?&quot;) \ &amp; can_access_blob?(send(&quot;current_#{self.class.auth_resource}&quot;)) if is_signed_in_and_authorized yield else head :unauthorized end end def can_access_blob?(_user) true end end </code></pre>
3,063,321
Is there an equivalent to COM on *nix systems ? If not, what was the *nix approach to re-usability?
<p>I have an understanding of windows COM and the ideas behind it. I am trying to understand if *nix systems even have an equivalent or why they don't?</p>
3,063,508
3
0
null
2010-06-17 15:52:40.85 UTC
21
2017-03-15 10:13:46.203 UTC
null
null
null
null
192,814
null
1
46
linux|unix|architecture|com
13,364
<p>The Unix model is built around the idea of lightweight processes that communicate with each other, through sockets, pipes, signals, and command lines. Historically, Unix didn't have threads (the POSIX thread model is only about 10 years old IIRC), but processes on Unix have always been much cheaper than on Windows, so it was more performant to factor functionality into separate executables than to allow a single program to grow large and monolithic.</p> <p>In COM, you define binary interfaces that allow shared-memory communication. COM is tied to an <em>object-oriented</em> paradigm. In the classic Unix model, you define stream-oriented interfaces that allow communication over pipes, without shared memory. Conceptually, this is much closer to a <em>functional</em> programming paradigm.</p> <p>The Unix model encourages making small programs that can be easily coupled together by a lightweight "shell", while the COM model encourages making large programs that expose "components" that can be reused by other large programs. It's really an apples-and-oranges comparison, since both models provide benefits and drawbacks for different scenarios.</p> <p>Of course, modern Unix systems can have COM-like facilities. Mozilla has XPCOM, a cross-platform framework built on the same principles as COM. GNOME for a long time used Bonobo, which is conceptually very similar to Microsoft OLE, which was the forerunner to COM. But recent versions of GNOME have been shifting away from Bonobo in favor of D-Bus, which is more of an event/messaging pattern.</p>
2,730,354
Spring scheduler shutdown error
<p>During development a SPRING based scheduler in a tomcat container, I always get this logoutput at undeploy webapp or shutdown server:</p> <pre><code>Apr 28, 2010 4:21:33 PM org.apache.catalina.core.StandardService stop INFO: Stopping service Catalina Apr 28, 2010 4:21:33 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads SEVERE: A web application appears to have started a thread named [org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-1] but has failed to stop it. This is very likely to create a memory leak. Apr 28, 2010 4:21:33 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads SEVERE: A web application appears to have started a thread named [org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-2] but has failed to stop it. This is very likely to create a memory leak. Apr 28, 2010 4:21:33 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads SEVERE: A web application appears to have started a thread named [org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-3] but has failed to stop it. This is very likely to create a memory leak. Apr 28, 2010 4:21:33 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads SEVERE: A web application appears to have started a thread named [org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-4] but has failed to stop it. This is very likely to create a memory leak. Apr 28, 2010 4:21:33 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads SEVERE: A web application appears to have started a thread named [org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-5] but has failed to stop it. This is very likely to create a memory leak. . . . SEVERE: A web application created a ThreadLocal with key of type [org.springframework.core.NamedThreadLocal] (value [Prototype beans currently in creation]) and a value of type [null] (value [null]) but failed to remove it when the web application was stopped. To prevent a memory leak, the ThreadLocal has been forcibly removed. Apr 28, 2010 4:21:34 PM org.apache.coyote.http11.Http11Protocol destroy INFO: Stopping Coyote HTTP/1.1 on http-8606 </code></pre> <p>How can I fix this?</p> <p>thank you <a href="https://stackoverflow.com/users/116880/stevedbrown">stevedbrown</a></p> <p>I add this listener to my webapp</p> <pre><code>public class ShutDownHook implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent arg0) { BeanFactory bf = (BeanFactory) ContextLoader.getCurrentWebApplicationContext(); if (bf instanceof ConfigurableApplicationContext) { ((ConfigurableApplicationContext)bf).close(); } } @Override public void contextInitialized(ServletContextEvent arg0) { } } </code></pre> <p>and my web.xml</p> <pre><code>&lt;listener&gt; &lt;listener-class&gt;pkg.utility.spring.ShutDownHook&lt;/listener-class&gt; &lt;/listener&gt; </code></pre> <p>but the error is still there.</p> <p>spring config:</p> <p> </p> <pre><code>&lt;bean id="run" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"&gt; &lt;property name="concurrent" value="false" /&gt; &lt;property name="targetObject" ref="scheduler" /&gt; &lt;property name="targetMethod" value="task" /&gt; &lt;/bean&gt; &lt;bean id="cronTrg" class="org.springframework.scheduling.quartz.CronTriggerBean"&gt; &lt;property name="jobDetail" ref="run" /&gt; &lt;property name="cronExpression" value="0/5 * * * * ?" /&gt; &lt;/bean&gt; &lt;bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean" destroy-method="destroy"&gt; &lt;property name="triggers"&gt; &lt;list&gt; &lt;ref bean="cronTrg" /&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; </code></pre>
2,732,227
4
1
null
2010-04-28 14:30:08.227 UTC
9
2013-03-07 12:09:44.32 UTC
2017-05-23 12:02:04.963 UTC
null
-1
null
275,837
null
1
15
java|spring|tomcat|quartz-scheduler
24,785
<p>You need to add a shutdown hook - see <a href="https://stackoverflow.com/questions/1827212/registering-a-shutdown-hook-in-spring-2-5">Registering a shutdown hook in Spring 2.5</a>.</p> <p>In your case, you probably should add a context listener to your webapp that does this (web.xml entry for the listener + implementing class).</p> <p>Use close, it's easiest.</p> <pre><code>((YourClass)yourObject).close(); </code></pre>
2,463,155
How to unescape XML characters with help of XSLT?
<p>I need to unescape XML characters from inside of XML nodes with the help of only XSLT transformations. I have <code>&lt;text&gt;&amp;lt;&amp;gt;and other possible characters&lt;/text&gt;</code> and need to get it as valid formatted HTML when I place it inside of the body tag.</p>
2,463,730
4
2
null
2010-03-17 14:44:13.773 UTC
10
2017-10-19 01:27:35.237 UTC
2015-09-11 04:35:57.053 UTC
null
212,378
null
290,570
null
1
20
xml|xslt
33,831
<pre><code>&lt;xsl:template match="text"&gt; &lt;body&gt; &lt;xsl:value-of select="." disable-output-escaping="yes" /&gt; &lt;/body&gt; &lt;/xsl:template&gt; </code></pre> <p>Note that the output is not guaranteed to be well-formed XML anymore.</p>
63,627,955
Can't load shared library libQt5Core.so.5
<p>This question has been asked before, but the fixes don't work for me. I am running Windows 10 with WSL (Debian) and I am unable to run a QT program because of the error</p> <p><code>texconv: error while loading shared libraries: libQt5Core.so.5: cannot open shared object file: No such file or directory</code></p> <p>I found <a href="https://askubuntu.com/questions/1034313/ubuntu-18-4-libqt5core-so-5-cannot-open-shared-object-file-no-such-file-or-dir">a post</a> which discusses the same problem. I've tried tolos' and Envek's solutions, but they don't work for me. For me the file is under <code>/usr/lib/x86_64-linux-gnu/</code> like tolos' was. I also sudo-ed the strip and recompiled the qt program (If that even matters), but it still doesn't work.</p> <p>If it matters, my kernel version (checked with <code>uname -r</code>) is 4.4.0-18362-Microsoft and I have no issues running this qt program on my other PC that uses WSL Ubuntu. And I installed the qt stuff with this command: <code>sudo apt-get install qt5-default qtbase5-dev</code></p>
63,654,633
2
0
null
2020-08-28 05:28:23.127 UTC
9
2021-08-23 18:01:51.907 UTC
2020-08-30 03:35:48.787 UTC
null
10,418,882
null
10,418,882
null
1
19
qt|debian|shared-libraries|windows-subsystem-for-linux
36,352
<p>I got it working in the end. I upgraded from WSLv1 to WSLv2 and that solved it. Not sure why, but it must have been a WSLv1 Debian bug</p>
38,732,025
Upload file to SFTP using PowerShell
<p>We were asked to set up an automated upload from one of our servers to an SFTP site. There will be a file that is exported from a database to a filer every Monday morning and they want the file to be uploaded to SFTP on Tuesday. The current authentication method we are using is username and password (I believe there was an option to have key file as well but username/password option was chosen).</p> <p>The way I am envisioning this is to have a script sitting on a server that will be triggered by Windows Task scheduler to run at a specific time (Tuesday) that will grab the file in question upload it to the SFTP and then move it to a different location for backup purposes.</p> <p>For example:</p> <ul> <li><p>Local Directory: <code>C:\FileDump</code></p></li> <li><p>SFTP Directory: <code>/Outbox/</code></p></li> <li><p>Backup Directory: <code>C:\Backup</code></p></li> </ul> <p>I tried few things at this point WinSCP being one of them as well as <a href="http://www.k-tools.nl/index.php/download-sftp-powershell-snap-in/" rel="noreferrer">SFTP PowerShell Snap-In</a> but nothing has worked for me so far. </p> <p>This will be running on Windows Server 2012R2.<br> When I run <code>Get-Host</code> my console host version is 4.0.</p> <p>Thanks.</p>
38,733,213
6
0
null
2016-08-02 23:28:40.253 UTC
20
2022-09-06 14:57:05.35 UTC
2020-01-03 15:22:41.357 UTC
null
850,848
null
6,042,554
null
1
42
powershell|automation|upload|sftp|winscp
162,439
<p>There isn't currently a built-in PowerShell method for doing the SFTP part. You'll have to use something like psftp.exe or a PowerShell module like Posh-SSH.</p> <p>Here is an example using <a href="http://www.powershellmagazine.com/2014/07/03/posh-ssh-open-source-ssh-powershell-module/" rel="noreferrer">Posh-SSH</a>:</p> <pre><code># Set the credentials $Password = ConvertTo-SecureString 'Password1' -AsPlainText -Force $Credential = New-Object System.Management.Automation.PSCredential ('root', $Password) # Set local file path, SFTP path, and the backup location path which I assume is an SMB path $FilePath = "C:\FileDump\test.txt" $SftpPath = '/Outbox' $SmbPath = '\\filer01\Backup' # Set the IP of the SFTP server $SftpIp = '10.209.26.105' # Load the Posh-SSH module Import-Module C:\Temp\Posh-SSH # Establish the SFTP connection $ThisSession = New-SFTPSession -ComputerName $SftpIp -Credential $Credential # Upload the file to the SFTP path Set-SFTPFile -SessionId ($ThisSession).SessionId -LocalFile $FilePath -RemotePath $SftpPath #Disconnect all SFTP Sessions Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) } # Copy the file to the SMB location Copy-Item -Path $FilePath -Destination $SmbPath </code></pre> <p>Some additional notes:</p> <ul> <li>You'll have to download the Posh-SSH module which you can install to your user module directory (e.g. C:\Users\jon_dechiro\Documents\WindowsPowerShell\Modules) and just load using the name or put it anywhere and load it like I have in the code above.</li> <li>If having the credentials in the script is not acceptable you'll have to use a credential file. If you need help with that I can update with some details or point you to some links.</li> <li>Change the paths, IPs, etc. as needed.</li> </ul> <p>That should give you a decent starting point.</p>
38,623,616
Is there any way to check what gulp version you have installed?
<p>Is there any way to check what gulp version you have installed and also what version of gulp is being offered by the website? I've searched online, and looked at the gulp website, but cannot find the version I need to put in my JSON file. </p>
38,623,658
2
1
null
2016-07-27 21:37:19.183 UTC
3
2021-07-22 16:38:19.947 UTC
null
null
null
null
6,407,868
null
1
36
html|json|git|gulp
70,659
<p>Simply use: <code>gulp -v</code></p> <p>From the docs:</p> <p><a href="https://github.com/gulpjs/gulp/blob/master/docs/CLI.md" rel="noreferrer">https://github.com/gulpjs/gulp/blob/master/docs/CLI.md</a></p>
49,783,178
Python Keep other columns when using sum() with groupby
<p>I have a pandas dataframe below:</p> <pre><code> df name value1 value2 otherstuff1 otherstuff2 0 Jack 1 1 1.19 2.39 1 Jack 1 2 1.19 2.39 2 Luke 0 1 1.08 1.08 3 Mark 0 1 3.45 3.45 4 Luke 1 0 1.08 1.08 </code></pre> <p>Same "name" will have the same value for otherstuff1 and otherstuff2.</p> <p>I'm trying to groupby by column 'name' and sum column 'value1' and sum column 'value2' (Not sum value1 with value2!!! But sum them individually in each column)</p> <p>Expecting to get result below:</p> <pre><code> newdf name value1 value2 otherstuff1 otherstuff2 0 Jack 2 3 1.19 2.39 1 Luke 1 1 1.08 1.08 2 Mark 0 1 3.45 3.45 </code></pre> <p>I've tried </p> <pre><code>newdf = df.groupby(['name'], as_index = False).sum() </code></pre> <p>which groupsby name and sums up both value1 and value2 columns correctly but end up dropping column otherstuff1 and otherstuff2.</p> <p>Please help. Thank you guys so much!</p>
49,783,218
4
0
null
2018-04-11 19:36:54.833 UTC
11
2022-08-07 10:27:49.487 UTC
null
null
null
null
3,914,955
null
1
42
python|pandas
49,942
<p>Something like ?(Assuming you have same otherstuff1 and otherstuff2 under the same name )</p> <pre><code>df.groupby(['name','otherstuff1','otherstuff2'],as_index=False).sum() Out[121]: name otherstuff1 otherstuff2 value1 value2 0 Jack 1.19 2.39 2 3 1 Luke 1.08 1.08 1 1 2 Mark 3.45 3.45 0 1 </code></pre>
35,127,257
How to get the size of a filtered (piped) set in angular2
<p>I wrote my own filter pipe as it disappeared in angular2:</p> <pre><code>import {Pipe, PipeTransform} from 'angular2/core'; @Pipe({ name: 'myFilter' }) export class MyFilter implements PipeTransform { transform(customerData: Array&lt;Object&gt;, args: any[]) { if (customerData == undefined) { return; } var re = new RegExp(args[0]); return customerData.filter((item) =&gt; re.test(item.customerId)); } } </code></pre> <p>And use it in my template:</p> <pre><code>&lt;tr *ngFor="#singleCustomerData of customerData | myFilter:searchTerm"&gt; ... &lt;/tr&gt; </code></pre> <p>Now I'd like to see how many matches the pipe returns. So essentially the size of the returned array.</p> <p>In angular 1.x we were able so assign the returned set to a variable in a template like so:</p> <pre><code>&lt;div ng-repeat="person in filtered = (data | filter: query)"&gt; &lt;/div&gt; </code></pre> <p>But we can no longer assign variables in templates in angular2.</p> <p>So how do I get the size of the filtered set without calling the filter twice?</p>
35,127,331
5
0
null
2016-02-01 09:43:22.053 UTC
4
2018-06-13 10:33:58.68 UTC
null
null
null
null
2,022,021
null
1
30
filter|typescript|pipe|angular
20,801
<p><strong>original</strong></p> <p>AFAIK there is currently no way to do this directly. A hack would be to add a template variable to the content and use a <code>ViewChildren(...)</code> query to get the created items and count them.</p> <pre><code>&lt;tr *ngFor="let singleCustomerData of customerData | myFilter:searchTerm" #someVar&gt; ... &lt;/tr&gt; &lt;div&gt;count: {{filteredItems?.length}}&lt;/div&gt; </code></pre> <pre><code>@ViewChildren('someVar') filteredItems; </code></pre> <p>An alternative approach would be to pass a reference to a counter variable to the pipe like shown in <a href="https://plnkr.co/edit/Eqjyt4qdnXezyFvCcGAL?p=preview" rel="noreferrer">https://plnkr.co/edit/Eqjyt4qdnXezyFvCcGAL?p=preview</a> </p> <p><strong>update (Angular >=4.0.0)</strong></p> <p>Since <a href="https://github.com/angular/angular/compare/4.0.0-rc.3...4.0.0-rc.4" rel="noreferrer">Angular 4</a> <code>*ngFor</code> supports <code>as</code></p> <pre><code>&lt;tr *ngFor="let singleCustomerData of customerData | myFilter:searchTerm as result"&gt; </code></pre> <p>which you can use in the template (inside the element that <code>*ngFor</code> is added to) like</p> <pre><code> &lt;div&gt;{{result?.length}}&lt;/div&gt; </code></pre>
50,189,364
Shouldn't the login be a Query in GraphQL?
<p>In the <a href="https://www.howtographql.com/graphql-js/6-authentication/" rel="noreferrer">tutorial</a> on GraphQL authentication, the <code>login</code> is a <strong>Mutation</strong>:</p> <pre><code>type Mutation { post(url: String!, description: String!): Link! signup(email: String!, password: String!, name: String!): AuthPayload login(email: String!, password: String!): AuthPayload } </code></pre> <p>Shouldn't the login be a <strong><em>Query</em></strong> since:</p> <ol> <li>The operation has no side-effects on the server.</li> <li>The goal is to <em>query</em> a token.</li> </ol> <p>Am I missing something here ?</p>
50,190,570
1
1
null
2018-05-05 12:19:02.147 UTC
17
2021-12-12 09:59:13.807 UTC
null
null
null
null
252,124
null
1
80
graphql
16,009
<p>In the context of that example, <code>login</code> should be a Query instead of a Mutation assuming its resolver has no side-effects, at least according to the spec. However, there's a couple of reasons you probably won't see that done in the wild:</p> <ul> <li><p>If you're implementing authentication, you'll probably want to log your users' account activity, either by maintaining some data about login/logout events or at least including some sort of "last login" field on the account's record. Modifying that data <em>would</em> be a side effect.</p></li> <li><p>A convention has evolved that treats any operations that result from user actions as Mutations, regardless of side-effects. You see this with <code>react-apollo</code>, for example, where <code>useQuery</code> fires the associated query on mount, while <code>useMutation</code> only provides a function that can be called to fire that query. If you're planning on using Apollo client-side, it's worthwhile to consider those sort of client features when designing your schema.</p></li> <li><p>Mutations are ran sequentially, while queries are ran simultaneously. That means it'd be foreseeable to fire a login mutation and one or more other mutations after it within the same call, allowing you to utilize an authenticated context for the subsequent calls. The same could not be said for queries -- if <code>login</code> is a query and you include other queries with it in the same operation, they will all begin resolving at the same time.</p></li> </ul> <p>Outside of how they're executed (sequentially vs simultaneously), on the server-side, queries and mutations are effectively interchangeable. You could have queries with side-effects and mutations with no side effects. You probably should stick with conventions, but I think sometimes there's valid reasons where you may have to throw those conventions out the window.</p>
45,023,201
Can't import packages using Swift 4 Package Manager
<p>Trying to test Swift 4 using Xcode-beta (v9) on my machine and having issues with importing packages into a test project:</p> <ul> <li>Initiated project using <code>swift package init --type executable</code></li> <li>Changed <code>Package.swift</code> and added 2 projects to try out:</li> </ul> <p><strong>Package.swift</strong></p> <pre><code>// swift-tools-version:4.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "sampleproject", dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), .package(url: "https://github.com/IBM-Swift/Kitura.git", from: "1.7.6"), .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.5.0") ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "sampleproject", dependencies: []), ] ) </code></pre> <ul> <li>Run <code>swift build &amp;&amp; swift package generate-xcodeproj</code></li> <li>When I open project in Xcode-beta(v9) and try to import Kitura or Alamofire, I'm getting <code>No such module Kitura/Alamofire</code> error message</li> <li>Running <code>swift build</code> in terminal produces the following error:</li> </ul> <blockquote> <p>Compile Swift Module 'investprosto' (1 sources) /Users/username/Projects/sampleproject/Sources/sampleproject/main.swift:1:8: error: no such module 'Kitura' import Kitura ^ error: terminated(1): /Applications/Xcode- beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift- build-tool -f /Users/username/Projects/sampleproject/.build/debug.yaml</p> </blockquote> <p><strong>Dependencies</strong> virtual folder contains the directories with the same package names, but they are empty. However, <code>.build\checkouts</code> and <code>.build\repositories</code> contain packages folders and corresponding files.</p> <p>Is there something I'm missing in my system's configuration?</p>
45,035,349
2
0
null
2017-07-10 23:38:43.743 UTC
11
2019-09-05 07:45:07.277 UTC
2017-07-12 07:00:57.247 UTC
null
5,624,053
null
793,167
null
1
33
swift|xcode|macos|package-managers|swift4
13,420
<p>Turns out I had to also include the dependencies into the <code>.target</code> of the Package.swift:</p> <pre><code>.target(named: "sampleproject", dependencies: ["Kitura", "Alamofire"]) </code></pre> <p>and build the project again.</p>
36,359,812
Spark can access Hive table from pyspark but not from spark-submit
<p>So, when running from pyspark i would type in (without specifying any contexts) :</p> <pre><code>df_openings_latest = sqlContext.sql('select * from experian_int_openings_latest_orc') </code></pre> <p>.. and it works fine.</p> <p>However, when i run my script from <code>spark-submit</code>, like </p> <p><code>spark-submit script.py</code> i put the following in </p> <pre><code>from pyspark.sql import SQLContext from pyspark import SparkConf, SparkContext conf = SparkConf().setAppName('inc_dd_openings') sc = SparkContext(conf=conf) sqlContext = SQLContext(sc) df_openings_latest = sqlContext.sql('select * from experian_int_openings_latest_orc') </code></pre> <p>But it gives me an error </p> <blockquote> <p>pyspark.sql.utils.AnalysisException: u'Table not found: experian_int_openings_latest_orc;'</p> </blockquote> <p>So it doesnt see my table. </p> <p>What am I doing wrong? Please help</p> <p>P.S. Spark version is 1.6 running on Amazon EMR</p>
36,360,168
4
0
null
2016-04-01 15:10:34.93 UTC
10
2022-07-29 06:44:56.693 UTC
2016-04-01 16:42:35.653 UTC
null
1,560,062
null
717,770
null
1
18
python|hadoop|apache-spark|pyspark
29,486
<p><strong>Spark 2.x</strong></p> <p>The same problem may occur in Spark 2.x if <code>SparkSession</code> has been created without <a href="https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.SparkSession$$Builder@enableHiveSupport():org.apache.spark.sql.SparkSession.Builder" rel="noreferrer">enabling Hive support</a>.</p> <p><strong>Spark 1.x</strong></p> <p>It is pretty simple. When you use PySpark shell, and Spark has been build with Hive support, default <code>SQLContext</code> implementation (the one available as a <code>sqlContext</code>) is <code>HiveContext</code>.</p> <p>In your standalone application you use plain <code>SQLContext</code> which doesn't provide Hive capabilities. </p> <p>Assuming the rest of the configuration is correct just replace:</p> <pre><code>from pyspark.sql import SQLContext sqlContext = SQLContext(sc) </code></pre> <p>with </p> <pre><code>from pyspark.sql import HiveContext sqlContext = HiveContext(sc) </code></pre>
36,578,863
How to decode base64 string and convert it into PDF/JPG and save it in storage
<p>I would like to decode a base64 string and turn it into a file (as PDF/JPG) and save it to device, how for example in (/storage/emulated/0/Download/file.pdf).</p> <p>For encode a file I use this code:</p> <pre><code>File originalFile = new File("/mnt/sdcard/download/file.pdf"); String encodedBase64 = null; try { FileInputStream fileInputStreamReader = new FileInputStream(originalFile); byte[] bytes = new byte[(int) originalFile.length()]; fileInputStreamReader.read(bytes); encodedBase64=Base64.encodeToString(bytes,Base64.NO_WRAP); messaggio=encodedBase64.toString(); //encodedBase64 = new String(Base64.encode(bytes)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } </code></pre> <p>Now, I would like to decode this base64 string and convert it into a file and save it on the device.</p>
36,579,004
2
0
null
2016-04-12 16:18:49.007 UTC
null
2019-12-28 13:00:01.85 UTC
2019-12-28 13:00:01.85 UTC
null
1,000,551
null
6,003,585
null
1
12
java|android|base64|fileoutputstream
58,731
<p>You can try this:</p> <pre><code>FileOutputStream fos = new FileOutputStream(filepath); fos.write(Base64.decode(base64String, Base64.NO_WRAP)); fos.close(); </code></pre> <p>Where:</p> <ul> <li><code>filepath:</code> Path to the new file</li> <li><code>base64String:</code> Your base64 string that you want to convert</li> </ul>
26,390,610
Static IP using Elastic Beanstalk
<p>I need the static IP to allow access to a firewalled network not on the AWS network.</p> <p>Is it possible to get a static IP for a load balanced app using Elastic Beanstalk? I'm following the <a href="http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/CreatingNewSubdomain.html#UpdateDNSParentDomain">AWS docs</a> regarding using Route 53 to host my app with a domain name, but from what I've read, this does not ensure a static IP because it is essentially using a CNAME allowing the IP behind the scenes to change. Is that the right understanding? Is it possible at all? </p>
38,969,589
3
0
null
2014-10-15 19:33:01.8 UTC
7
2020-10-13 17:39:45.71 UTC
null
null
null
null
163,630
null
1
29
amazon-web-services|amazon-elastic-beanstalk|amazon-route53
25,117
<p>Deploy your beanstalk environment in VPC, and with the right configuration, a static IP for outbound traffic is easy.</p> <p>In this setup, your instances all relay their outbound traffic through a single machine, which you can assign an elastic IP address to. All of the inside-originated, Internet-bound traffic from all of the instances behind it will appear, from the other network, to bw using that single elastic IP.</p> <p>The RDS portion of the following may be irrelevant to your needs but the principles are all the same.</p> <p><a href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/AWSHowTo-vpc-rds.html" rel="nofollow noreferrer">http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/AWSHowTo-vpc-rds.html</a></p>
40,355,403
mongoose getting `TypeError: user.save is not a function` - what is wrong
<p>I am trying to post the user data to <code>mongodb</code> but I am getting an error as : </p> <p>`TypeError: user.save is not a function' - how to fix this?</p> <p>here is my code :</p> <pre><code>var express = require('express'), app = express(), bodyParser = require('body-parser'), mongoose = require('mongoose'), PORT = process.env.PORT || 8080; //connect to db mongoose.connect('mongodb://3gwebtrain:[email protected]:47975/family'); app.use( bodyParser.urlencoded({extended : true })); app.use( bodyParser.json() ); app.get('/', function( req, res ) { res.json({message:'works'}) }); var Schema = mongoose.Schema; var User = new Schema({ name:String, username:{type:String, required:true, index:{unique:true}}, password:{type:String, required:true, select:false} }) var apiRouter = express.Router(); apiRouter .get('/users', function( req, res ){ res.send( "yet to get users!"); }) .post('/users', function( req, res ) { var user = User; user.name = req.body.name; user.username = req.body.username; user.password = req.body.password; user.save(function(err) { if( err ) { console.log( err ); //TypeError: user.save is not a function } res.send("user created!"); }) }) app.use('/api', apiRouter); app.listen( PORT ); console.log( 'app listens at ' + PORT ); </code></pre>
40,355,688
3
1
null
2016-11-01 06:59:15.793 UTC
4
2020-03-02 18:57:24.023 UTC
null
null
null
null
218,349
null
1
21
node.js|mongodb|mongoose
45,456
<p>first create model from Schema :</p> <pre><code> var UserModel = mongoose.model('User', User); </code></pre> <p>then create object out of User model </p> <pre><code> var user = new UserModel(req.body) </code></pre> <p>then call </p> <pre><code> user.save(function(){}) </code></pre> <p>check documentation <a href="http://mongoosejs.com/docs/api.html#model_Model-save" rel="noreferrer">http://mongoosejs.com/docs/api.html#model_Model-save</a></p>
2,486,999
When should I use FrameworkPropertyMetadata or UIPropertyMetadata over plain PropertyMetadata?
<p>When looking at sample attached properties and behaviors, I've seen a mishmash of uses of <code>FrameworkPropertyMetadata</code>, <code>UIPropertyMetadata</code> and <code>PropertyMetadata</code>. Since they all form an inheritance hierarchy, how do I choose which one to use?</p>
2,487,060
1
0
null
2010-03-21 12:11:42.13 UTC
21
2013-02-22 08:28:38.007 UTC
null
null
null
null
8,446
null
1
86
wpf|attached-properties|attachedbehaviors
23,660
<p>These classes are to report some behavior aspects of a dependency property.</p> <p>Check the different classes for the options they provide.</p> <p>For example, </p> <p>if you just want to back a property by dp and provide a default value, use <code>PropertyMetadata</code>,</p> <p>if you want to specify animation behavior, use <code>UIPropertyMetadata</code>,</p> <p>but if some property affects wpf framework level stuffs eg element layout, parent layout or databinding, use <code>FrameworkPropertyMetadata</code>.</p> <p>Details you can check on msdn <a href="http://msdn.microsoft.com/en-us/library/ms751554.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms751554.aspx</a></p>
33,973,648
React: "this" is undefined inside a component function
<pre><code>class PlayerControls extends React.Component { constructor(props) { super(props) this.state = { loopActive: false, shuffleActive: false, } } render() { var shuffleClassName = this.state.toggleActive ? "player-control-icon active" : "player-control-icon" return ( &lt;div className="player-controls"&gt; &lt;FontAwesome className="player-control-icon" name='refresh' onClick={this.onToggleLoop} spin={this.state.loopActive} /&gt; &lt;FontAwesome className={shuffleClassName} name='random' onClick={this.onToggleShuffle} /&gt; &lt;/div&gt; ); } onToggleLoop(event) { // "this is undefined??" &lt;--- here this.setState({loopActive: !this.state.loopActive}) this.props.onToggleLoop() } </code></pre> <p>I want to update <code>loopActive</code> state on toggle, but <code>this</code> object is undefined in the handler. According to the tutorial doc, I <code>this</code> should refer to the component. Am I missing something?</p>
33,973,758
11
0
null
2015-11-28 16:30:26.873 UTC
34
2022-07-25 14:41:34.127 UTC
2020-01-19 07:02:35.053 UTC
null
1,218,980
null
1,815,412
null
1
208
javascript|reactjs|this
159,007
<p>ES6 <code>React.Component</code> doesn't auto bind methods to itself. You need to bind them yourself in <code>constructor</code>. Like this:</p> <pre><code>constructor (props){ super(props); this.state = { loopActive: false, shuffleActive: false, }; this.onToggleLoop = this.onToggleLoop.bind(this); } </code></pre>
38,556,327
Any free version of SQL Server?
<p>Is there a free version of SQL Server where one can practice or any other tool which checks correct SQL Server syntax?</p> <p>I would like an offline one.</p> <p>I am expecting something like OracleXE server.</p>
38,556,342
1
2
null
2016-07-24 20:13:25.61 UTC
1
2020-09-19 07:00:28.26 UTC
2018-04-09 05:31:17.017 UTC
null
3,492,866
null
3,492,866
null
1
6
sql-server
59,528
<p>What you are looking for is SQL Express Edition. It is the free version with limitations.</p> <p>Link: <a href="https://www.microsoft.com/en-us/cloud-platform/sql-server-editions-express" rel="nofollow noreferrer">https://www.microsoft.com/en-us/cloud-platform/sql-server-editions-express</a></p> <p>If you want all the features of SQL Server Enterprise edition to test then you need Developer Edition.</p> <p><a href="https://www.infoq.com/news/2016/06/SQL-Developer-Free" rel="nofollow noreferrer">https://www.infoq.com/news/2016/06/SQL-Developer-Free</a></p> <p><strong>Edit:</strong> To marc_s point here is the blog post from MSFT about MSSQL Developer Edition being free: <a href="https://blogs.technet.microsoft.com/dataplatforminsider/2016/03/31/microsoft-sql-server-developer-edition-is-now-free/" rel="nofollow noreferrer">https://blogs.technet.microsoft.com/dataplatforminsider/2016/03/31/microsoft-sql-server-developer-edition-is-now-free/</a></p> <p>All you need to do is sign up for the &quot;Dev Essentials&quot; (Free):</p> <p><a href="https://www.visualstudio.com/products/visual-studio-dev-essentials-vs" rel="nofollow noreferrer">https://www.visualstudio.com/products/visual-studio-dev-essentials-vs</a></p>
6,135,942
ManagedProperty not injected in @FacesConverter
<p>I'm trying to inject a ManagedBean in my FacesConverted the following way:</p> <pre><code>@ManagedBean @RequestScoped @FacesConverter(forClass = Group.class) public class GroupConverter implements Converter { @ManagedProperty("#{groupService}") private GroupService groupService; @Override public Group getAsObject(FacesContext context, UIComponent arg1, String groupName) { return groupService.findGroupByName(groupName); } @Override public String getAsString(FacesContext arg0, UIComponent arg1, Object group) { return ((Group) group).getName(); } public GroupService getGroupService() { return groupService; } public void setGroupService(GroupService groupService) { this.groupService = groupService; } } </code></pre> <p>The problem is that groupService isn't being injected and I get a NullPointerEx. Shouldn't it be autowired automatically since it's also a ManagedBean? It all works when I change "getAsObject" to "return new Group();" obviously.</p> <p>Any ideas?</p>
6,137,011
1
0
null
2011-05-26 08:52:02.143 UTC
10
2012-11-16 11:56:45.27 UTC
null
null
null
null
217,019
null
1
10
jsf|dependency-injection|jsf-2|converter|managed-bean
8,926
<p>It is likely that you are not resolving the <a href="http://download.oracle.com/javaee/6/api/javax/faces/bean/ManagedBean.html#name%28%29">managed bean name</a>.</p> <pre><code>@ManagedBean(name = "myConverter") @RequestScoped @FacesConverter(value = "myConverter") public class MyConverter implements Converter { </code></pre> <p>For example, consider these two components:</p> <pre><code> &lt;h:inputText converter="myConverter" value="#{foo.prop}" /&gt; &lt;h:inputText converter="#{myConverter}" value="#{bar.prop}" /&gt; </code></pre> <p>When the converter is set on the first component, it will be created by <a href="http://download.oracle.com/javaee/6/api/javax/faces/application/Application.html#createConverter%28java.lang.String%29">Application.createConverter</a>. <strong>A converter is not a managed bean</strong>. The same rules apply if you <a href="http://download.oracle.com/javaee/6/api/javax/faces/application/Application.html#createConverter%28java.lang.Class%29">match a converter by type</a>.</p> <p>In the second component, a value expression is used to return a class that implements <a href="http://download.oracle.com/javaee/6/api/javax/faces/convert/Converter.html">Converter</a>. This uses the usual managed bean mechanisms. In this case, the <code>@FacesConverter</code> annotation is irrelevant.</p>
35,726,134
3D Plane fitting algorithms
<p>So I'm working on a project where me and a buddy of mine scanned a room using the KINECTv2 and made a 3D model out of it. The goal is to make it possible to add 3d models of different kinds of furniture in real time. To that goal I'm trying out different plane-fitting algorithms in order to find wich one would work the fastest. Does anybody have any suggestions? So far I've only researched the usage of the basic RANSAC algorithm included in PCL.</p>
35,738,435
2
0
null
2016-03-01 14:55:51.843 UTC
12
2017-01-09 21:28:48.297 UTC
null
null
null
null
6,003,123
null
1
5
algorithm|3d|plane|printer-control-language
16,153
<p>Two common approaches for plane fitting are RANSAC and Hough. Here's one performance comparison:</p> <p><a href="https://www.researchgate.net/publication/259519997_Continuous_plane_detection_in_point-cloud_data_based_on_3D_Hough_Transform" rel="noreferrer">https://www.researchgate.net/publication/259519997_Continuous_plane_detection_in_point-cloud_data_based_on_3D_Hough_Transform</a></p> <p>As with many problems in computational geometry and image processing, rather than consider what is "fastest," consider what is optimal for your application in terms of performance, development effort, and cost. Searching for the fastest possible algorithm could lead you down a path of horrifying cost and complexity, whereas you may able to implement a data processing chain of relatively simpler algorithms that run just fast enough to present a smooth and pleasant experience to the user.</p> <p>Long story short, I recommend starting with a Hough plane fit. Hough transform algorithms are relatively easy to write (once you grasp the basics), and tweaking parameters is intuitive.</p> <p><a href="https://en.wikipedia.org/wiki/Hough_transform" rel="noreferrer">https://en.wikipedia.org/wiki/Hough_transform</a></p> <p>One of the reasons to write your own algorithm is that you'll be in a better position to understand what changes need to be made once (not if) you discover the point cloud data is noisier and less well behaved than one would like.</p> <p>Achieving good speed is going to rely on a number of factors, including these:</p> <ul> <li>Point cloud pre-processing. Look for ways to break up the point cloud into chunks that can be processed more quickly.</li> <li>Parameterization. Once data is preprocessed, you can define narrower search bounds for your plane fit algorithm. For example, only try plane fits within a few degrees of vertical. You'll also need to choose parameters to find a balance between speed and quality of fit. </li> <li>Quality of the 3D data. That's a big topic by itself, and the sooner you can take a close look at the problems in the data the better.</li> <li>What "real time" means. Even for 3D graphics applications that involve user interaction, achieving real time based strictly on specs (updates at N frames/second) may be less important than presenting a smooth and simple interface.</li> <li>Multithreading and parallelism.</li> <li>3D display. Another big topic. </li> </ul> <p><strong>Pre-processing.</strong> You don't need to fit planes of arbitrary size to arbitrary point clouds: instead, you need to fit walls and maybe floors and ceilings. For Hough algorithms this means you can limit the range over which parameters are tested, and hence speed up processing. </p> <p>Rather than try to find all the plane fits for the complete, original point cloud, find ways to break up the point cloud into clusters of subclouds to which plane fit tests can be run more efficiently. </p> <p>PCL can calculate surface normals for you. If you can identify clusters of surface normals pointed in roughly the same direction, and then try plane fits for individual clusters, you should be able to speed things up considerably.</p> <p>Also, for your first pass you'll probably want to downsample your data and try fits on relatively fewer points. This is analogous to creating an "image pyramid" for 2D processing. </p> <p>Octrees are nice, simple means of dividing up space for queries, collision tests, and so on. An octree divides a space into eight nodes or "octants." This can be imagined as cutting a cube into eight smaller cubes. Then each octant is further divided into eight octants, and so on. If an octant (a node) doesn't contain points, you don't need to divide it further. </p> <p><a href="https://en.wikipedia.org/wiki/Octree" rel="noreferrer">https://en.wikipedia.org/wiki/Octree</a></p> <p><strong>Parameterization.</strong> The descriptions above should make it clear that if you can preprocess the data by simplifying and/or breaking up the original raw point cloud, then you'll be able to test much more narrowly defined searches that will run more quickly.</p> <p>For that matter, you probably don't need high accuracy in plane fits. You can generate reasonably good fits, then tweak those fits to generate ceilings, walls, and floors at right angles to each other.</p> <p><strong>3D data quality.</strong> The Kinect v2 is a time-of-flight device with some inherent measurement accuracy problems. For example, if you take a single image of a flat wall and then check the depth values, you'll notice some non-planar goofiness in the corners of the image. If you take a look at the range (or standard deviation) of depth values at each (x,y) pixel over multiple images, then you'll also notice differences in noisiness between center pixels and edge pixels.</p> <p>Once you perform a plane fit, generate a measure of the fit quality. This requires going back through the data to calculate point-to-plane distances for the points used for calculation. (To speed this up, only use every Nth point or randomly sample the points.) As you tinker with parameters you'll see the effects in terms of speed and fit quality.</p> <p><strong>Real time vs. Perceptibly smooth.</strong> If you only need the user to move furniture around in real time, it should be okay to spend longer generating the initial plane fits. </p> <p><strong>Multithreading/Parallelism</strong> To handle data input, plane fitting, and user interface you'll almost certain have to think hard about multithreading. To test algorithms you do work on the UI thread just to get started, but this is limiting.</p> <p>An application like this begs for CUDA or OpenCL. For the 3D display you'll be using the graphics card anyway. Although you don't need to jump into GPU programming right away, it's helpful to keep in mind how algorithms could be parallelized.</p> <p><strong>3D display.</strong> Were you planning to use Direct3D or OpenGL for 3D display and interaction? Implementing software to allow the user to "add 3d models of different kinds of furniture in real time" suggests you'll have to rely on the graphics card.</p> <p>If you can display the point cloud in a 3D view, maybe you don't even need plane fits. You might even get away with collision detection: if the 3D model of a chair bumps into a cluster of points (i.e. a wall), then you might just detect that collision rather than try to fit planes to define bounds. Octants and other space-dividing techniques will help speed up collision tests.</p> <p>The company Matterport (<a href="http://matterport.com/" rel="noreferrer">http://matterport.com/</a>) has developed something very much like what you're describing. If nothing else you can give their software a try and consider what might be improved/adapted for your needs.</p>
35,534,479
AngularJS 1.5+ Components do not support Watchers, what is the work around?
<p>I've been upgrading my custom directives to the new <a href="https://docs.angularjs.org/guide/component#component-based-application-architecture" rel="nofollow noreferrer">component architecture</a>. I've read that components do not support watchers. Is this correct? If so how do you detect changes on an object? For a basic example I have custom component <code>myBox</code> which has a child component game with a binding on the game . If there is a change game within the game component how do I show an alert message within the myBox? I understand there is rxJS method is it possible to do this purely in angular? My <a href="https://jsfiddle.net/bkarv/swv22g3s/" rel="nofollow noreferrer">JSFiddle</a></p> <p><strong>JavaScript</strong></p> <pre><code>var app = angular.module('myApp', []); app.controller('mainCtrl', function($scope) { $scope.name = "Tony Danza"; }); app.component("myBox", { bindings: {}, controller: function($element) { var myBox = this; myBox.game = 'World Of warcraft'; //IF myBox.game changes, show alert message 'NAME CHANGE' }, controllerAs: 'myBox', templateUrl: "/template", transclude: true }) app.component("game", { bindings: {game:'='}, controller: function($element) { var game = this; }, controllerAs: 'game', templateUrl: "/template2" }) </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;div ng-app="myApp" ng-controller="mainCtrl"&gt; &lt;script type="text/ng-template" id="/template"&gt; &lt;div style='width:40%;border:2px solid black;background-color:yellow'&gt; Your Favourite game is: {{myBox.game}} &lt;game game='myBox.game'&gt;&lt;/game&gt; &lt;/div&gt; &lt;/script&gt; &lt;script type="text/ng-template" id="/template2"&gt; &lt;div&gt; &lt;/br&gt; Change Game &lt;textarea ng-model='game.game'&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;/script&gt; Hi {{name}} &lt;my-box&gt; &lt;/my-box&gt; &lt;/div&gt;&lt;!--end app--&gt; </code></pre>
35,535,336
7
0
null
2016-02-21 09:33:47.953 UTC
52
2019-01-21 13:49:29.437 UTC
2019-01-21 13:49:29.437 UTC
null
5,827,612
null
4,376,500
null
1
78
angularjs|angularjs-directive|angularjs-scope|angularjs-components|angularjs-1.5
59,494
<h2>Writing Components without <a href="https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch" rel="noreferrer">Watchers</a></h2> <p>This answer outlines five techniques to use to write AngularJS 1.5 components without using <a href="https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch" rel="noreferrer">watchers.</a></p> <ul> <li>Use the <a href="https://docs.angularjs.org/api/ng/directive/ngChange" rel="noreferrer"><code>ng-change</code> Directive</a></li> <li>Use the <a href="https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks" rel="noreferrer"><code>$onChanges</code> Life-cycle Hook</a></li> <li>Use the <a href="https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks" rel="noreferrer"><code>$doCheck</code> Life-cycle Hook</a></li> <li>Intercomponent Communication with <a href="https://docs.angularjs.org/api/ng/service/$compile#-require-" rel="noreferrer">require</a></li> <li>Push Values from a Service with <a href="https://github.com/Reactive-Extensions/rx.angular.js" rel="noreferrer">RxJS</a></li> </ul> <hr> <h2>Use the <code>ng-change</code> Directive</h2> <blockquote> <p>what alt methods available to observe obj state changes without using watch in preparation for AngularJs2?</p> </blockquote> <p>You can use the <code>ng-change</code> directive to react to input changes.</p> <pre><code>&lt;textarea ng-model='game.game' ng-change="game.textChange(game.game)"&gt; &lt;/textarea&gt; </code></pre> <p>And to propagate the event to a parent component, the event handler needs to be added as an attribute of the child component.</p> <pre><code>&lt;game game='myBox.game' game-change='myBox.gameChange($value)'&gt;&lt;/game&gt; </code></pre> <p>JS</p> <pre><code>app.component("game", { bindings: {game:'=', gameChange: '&amp;'}, controller: function() { var game = this; game.textChange = function (value) { game.gameChange({$value: value}); }); }, controllerAs: 'game', templateUrl: "/template2" }); </code></pre> <p>And in the parent component:</p> <pre><code>myBox.gameChange = function(newValue) { console.log(newValue); }); </code></pre> <p>This is the preferred method going forward. The AngularJS strategy of using <code>$watch</code> is not scalable because it is a polling strategy. When the number of <code>$watch</code> listeners reaches around 2000, the UI gets sluggish. The strategy in Angular 2 is to make the framework more reactive and avoid placing <code>$watch</code> on <code>$scope</code>.</p> <hr> <h2>Use the <code>$onChanges</code> Life-cycle Hook</h2> <p>With <strong>version 1.5.3</strong>, AngularJS added the <code>$onChanges</code> life-cycle hook to the <code>$compile</code> service.</p> <p>From the Docs:</p> <blockquote> <p>The controller can provide the following methods that act as life-cycle hooks:</p> <ul> <li>$onChanges(changesObj) - Called whenever one-way (<code>&lt;</code>) or interpolation (<code>@</code>) bindings are updated. The <code>changesObj</code> is a hash whose keys are the names of the bound properties that have changed, and the values are an object of the form <code>{ currentValue: ..., previousValue: ... }</code>. Use this hook to trigger updates within a component such as cloning the bound value to prevent accidental mutation of the outer value.</li> </ul> <p><a href="https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks" rel="noreferrer">&#8212; AngularJS Comprehensive Directive API Reference -- Life-cycle hooks</a></p> </blockquote> <p>The <code>$onChanges</code> hook is used to react to external changes into the component with <code>&lt;</code> one-way bindings. The <code>ng-change</code> directive is used to propogate changes from the <code>ng-model</code> controller outside the component with <code>&amp;</code> bindings. </p> <hr> <h2>Use the <code>$doCheck</code> Life-cycle Hook</h2> <p>With <strong>version 1.5.8</strong>, AngularJS added the <code>$doCheck</code> life-cycle hook to the <code>$compile</code> service.</p> <p>From the Docs:</p> <blockquote> <p>The controller can provide the following methods that act as life-cycle hooks:</p> <ul> <li><code>$doCheck()</code> - Called on each turn of the digest cycle. Provides an opportunity to detect and act on changes. Any actions that you wish to take in response to the changes that you detect must be invoked from this hook; implementing this has no effect on when <code>$onChanges</code> is called. For example, this hook could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not be detected by Angular's change detector and thus not trigger <code>$onChanges</code>. This hook is invoked with no arguments; if detecting changes, you must store the previous value(s) for comparison to the current values.</li> </ul> <p><a href="https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks" rel="noreferrer">&#8212; AngularJS Comprehensive Directive API Reference -- Life-cycle hooks</a></p> </blockquote> <hr> <h1>Intercomponent Communication with <code>require</code></h1> <p>Directives can <a href="https://docs.angularjs.org/api/ng/service/$compile#-require-" rel="noreferrer">require</a> the controllers of other directives to enable communication between each other. This can be achieved in a component by providing an object mapping for the <a href="https://docs.angularjs.org/api/ng/service/$compile#-require-" rel="noreferrer">require</a> property. The object keys specify the property names under which the required controllers (object values) will be bound to the requiring component's controller.</p> <pre><code>app.component('myPane', { transclude: true, require: { tabsCtrl: '^myTabs' }, bindings: { title: '@' }, controller: function() { this.$onInit = function() { this.tabsCtrl.addPane(this); console.log(this); }; }, templateUrl: 'my-pane.html' }); </code></pre> <p>For more information, see <a href="https://docs.angularjs.org/guide/component#intercomponent-communication" rel="noreferrer">AngularJS Developer Guide - Intercomponent Communicatation</a></p> <hr> <h1>Push Values from a Service with <a href="https://github.com/Reactive-Extensions/rx.angular.js" rel="noreferrer">RxJS</a></h1> <blockquote> <p>What about in a situation where you have a Service that's holding state for example. How could I push changes to that Service, and other random components on the page be aware of such a change? Been struggling with tackling this problem lately</p> </blockquote> <p>Build a service with <a href="https://github.com/Reactive-Extensions/rx.angular.js" rel="noreferrer">RxJS Extensions for Angular</a>.</p> <pre><code>&lt;script src="//unpkg.com/angular/angular.js"&gt;&lt;/script&gt; &lt;script src="//unpkg.com/rx/dist/rx.all.js"&gt;&lt;/script&gt; &lt;script src="//unpkg.com/rx-angular/dist/rx.angular.js"&gt;&lt;/script&gt; </code></pre> <pre><code>var app = angular.module('myApp', ['rx']); app.factory("DataService", function(rx) { var subject = new rx.Subject(); var data = "Initial"; return { set: function set(d){ data = d; subject.onNext(d); }, get: function get() { return data; }, subscribe: function (o) { return subject.subscribe(o); } }; }); </code></pre> <p>Then simply subscribe to the changes.</p> <pre><code>app.controller('displayCtrl', function(DataService) { var $ctrl = this; $ctrl.data = DataService.get(); var subscription = DataService.subscribe(function onNext(d) { $ctrl.data = d; }); this.$onDestroy = function() { subscription.dispose(); }; }); </code></pre> <p>Clients can subscribe to changes with <code>DataService.subscribe</code> and producers can push changes with <code>DataService.set</code>. </p> <p>The <a href="https://plnkr.co/edit/YVKGhCx0DrzyzckMDjtv?p=preview" rel="noreferrer">DEMO on PLNKR</a>.</p>
25,414,347
How do I run a beam file compiled by Elixir or Erlang?
<p>I have installed Erlang/OTP and Elixir, and compiled the HelloWorld program into a BEAM using the command:</p> <pre><code>elixirc test.ex </code></pre> <p>Which produced a file named Elixir.Hello.beam</p> <p>How do I run this file?</p>
25,415,268
3
0
null
2014-08-20 21:01:37.107 UTC
14
2016-11-17 07:10:49.443 UTC
2014-08-21 17:32:16.75 UTC
null
815,724
null
340,811
null
1
29
erlang|elixir
18,478
<p>Short answer: no way to know for sure without also knowing the contents of your source file :)</p> <p>There are a few ways to run Elixir code. This answer will be an overview of various workflows that can be used with Elixir.</p> <p>When you are just getting started and want to try things out, launching <code>iex</code> and evaluating expressions one at a time is the way to go.</p> <pre><code>iex(5)&gt; Enum.reverse [1,2,3,4] [4, 3, 2, 1] </code></pre> <p>You can also get help on Elixir modules and functions in <code>iex</code>. Most of the functions have examples in their docs.</p> <pre><code>iex(6)&gt; h Enum.reverse def reverse(collection) Reverses the collection. [...] </code></pre> <hr> <p>When you want to put some code into a file to reuse it later, the recommended (and de facto standard) way is to create a mix project and start adding modules to it. But perhaps, you would like to know what's going on under the covers before relying on mix to perform common tasks like compiling code, starting applications, and so on. Let me explain that.</p> <p>The simplest way to put some expressions into a file and run it would be to use the <code>elixir</code> command.</p> <pre><code>x = :math.sqrt(1234) IO.puts "Your square root is #{x}" </code></pre> <p>Put the above fragment of code into a file named <code>simple.exs</code> and run it with <code>elixir simple.exs</code>. The <code>.exs</code> extension is just a convention to indicate that the file is meant to be evaluated (and that is what we did).</p> <p>This works up until the point you want to start building a project. Then you will need to organize your code into modules. Each module is a collection of functions. It is also the minimal compilation unit: each module is compiled into a <code>.beam</code> file. Usually people have one module per source file, but it is also fine to define more than one. Regardless of the number of modules in a single source file, each module will end up in its own <code>.beam</code> file when compiled.</p> <pre><code>defmodule M do def hi(name) do IO.puts "Hello, #{name}" end end </code></pre> <p>We have defined a module with a single function. Save it to a file named <code>mymod.ex</code>. We can use it in multiple ways:</p> <ul> <li><p>launch <code>iex</code> and evaluate the code in the spawned shell session:</p> <pre><code>$ iex mymod.ex iex&gt; M.hi "Alex" Hello, Alex :ok </code></pre></li> <li><p>evaluate it before running some other code. For example, to evaluate a single expression on the command line, use <code>elixir -e &lt;expr&gt;</code>. You can "require" (basically, evaluate and load) one or more files before it:</p> <pre><code>$ elixir -r mymod.ex -e 'M.hi "Alex"' Hello, Alex </code></pre></li> <li><p>compile it and let the code loading facility of the VM find it</p> <pre><code>$ elixirc mymod.ex $ iex iex&gt; M.hi "Alex" Hello, Alex :ok </code></pre></li> </ul> <p>In that last example we compiled the module which produced a file named <code>Elixir.M.beam</code> in the current directory. When you then run <code>iex</code> in the same directory, the module will be loaded the first time a function from it is called. You could also use other ways to evaluate code, like <code>elixir -e 'M.hi "..."'</code>. As long as the <code>.beam</code> file can be found by the code loader, the module will be loaded and the appropriate function in it will be executed.</p> <hr> <p>However, this was all about trying to play with some code examples. When you are ready to build a project in Elixir, you will need to use <code>mix</code>. The workflow with <code>mix</code> is more or less as follows:</p> <pre><code>$ mix new myproj * creating README.md * creating .gitignore * creating mix.exs [...] $ cd myproj # 'mix new' has generated a dummy test for you # see test/myproj_test.exs $ mix test </code></pre> <p>Add new modules in the <code>lib/</code> directory. It is customary to prefix all module names with your project name. So if you take the <code>M</code> module we defined above and put it into the file <code>lib/m.ex</code>, it'll look like this:</p> <pre><code> defmodule Myproj.M do def hi(name) do IO.puts "Hello, #{name}" end end </code></pre> <p>Now you can start a shell with the Mix project loaded in it.</p> <pre><code> $ iex -S mix </code></pre> <p>Running the above will compile all your source file and will put them under the <code>_build</code> directory. Mix will also set up the code path for you so that the code loader can locate <code>.beam</code> files in that directory.</p> <p>Evaluating expressions in the context of a mix project looks like this:</p> <pre><code>$ mix run -e 'Myproj.M.hi "..."' </code></pre> <p>Again, no need to compile anything. Most mix tasks will recompile any changed files, so you can safely assume that any modules you have defined are available when you call functions from them.</p> <p>Run <code>mix help</code> to see all available tasks and <code>mix help &lt;task&gt;</code> to get a detailed description of a particular task.</p>
51,247,609
Difference between docker run and docker container run
<p>Can anyone help me in the understanding difference between <strong>docker run</strong> &amp; <strong>docker container run</strong>?</p> <p>when i do <strong>docker run --help</strong> &amp; <strong>docker container run --help</strong> from docker cmd line. I see the following</p> <p><strong>Run a command in a new container</strong>.</p> <p>Is there any difference in how they run the container internally or both are same doing same work?</p> <p>As per <a href="https://forums.docker.com/t/docker-run-and-docker-container-run/30526" rel="noreferrer">https://forums.docker.com/t/docker-run-and-docker-container-run/30526</a>. <strong>docker run</strong> is still the old one, which will be deprecated soon but same is not confirmed.</p>
51,247,809
3
0
null
2018-07-09 14:10:09.427 UTC
12
2022-03-03 06:48:29.233 UTC
2022-03-03 06:48:29.233 UTC
null
3,098,330
null
7,158,227
null
1
91
docker
20,113
<p>They are exactly the same.</p> <p>Prior to docker 1.13 the <code>docker run</code> command was only available. The CLI commands were then refactored to have the form <code>docker COMMAND SUBCOMMAND</code>, wherein this case the COMMAND is <code>container</code> and the SUBCOMMAND is <code>run</code>. This was done to have a more intuitive grouping of commands since the number of commands at the time has grown substantially.</p> <p>You can read more under <a href="https://blog.docker.com/2017/01/whats-new-in-docker-1-13/" rel="noreferrer">CLI restructured</a>.</p>
38,338,475
'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync
<blockquote> <p>.Net Core 1.0.0 - SDK Preview 2 (x64)</p> <p>.Net Core 1.0.0 - VS &quot;15&quot; Preview 2 (x64)</p> <p>.Net Core 1.0.0 - Runtime (x64)</p> </blockquote> <p>So, we updated an RC1 app to the latest versions above. After many hours of switching references, it's running. However, when logging in (AccountController/Login), I am getting an error at:</p> <pre><code>public class AccountController : BaseController { public UserManager&lt;ApplicationUser&gt; UserManager { get; private set; } public SignInManager&lt;ApplicationUser&gt; SignInManager { get; private set; } private readonly IEmailSender EmailSender; public AccountController(UserManager&lt;ApplicationUser&gt; userManager, SignInManager&lt;ApplicationUser&gt; signInManager, IEmailSender emailSender) { UserManager = userManager; SignInManager = signInManager; EmailSender = emailSender; } // GET: /Account/Login [HttpGet] [AllowAnonymous] public IActionResult Login(string returnUrl = null) { ViewBag.ReturnUrl = returnUrl; return View(); } // // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task&lt;IActionResult&gt; Login(ViewModels.Account.LoginViewModel model, string returnUrl = null) { if (ModelState.IsValid) { // Errs this next line var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false); // &lt;-- ERRS HERE '.PasswordSignInAsync' if (result.Succeeded) return RedirectToLocal(returnUrl); ModelState.AddModelError(&quot;&quot;, &quot;Invalid email or password.&quot;); return View(model); } // If we got this far, something failed, redisplay form return View(model); } </code></pre> <p>It blows up with the following error message:</p> <blockquote> <p>InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.</p> </blockquote> <p>Here is the Startup.cs:</p> <pre><code>public void ConfigureServices(IServiceCollection services) { services.Configure&lt;AppSettings&gt;(Configuration.GetSection(&quot;AppSettings&quot;)); // Add EF services to the services container. services.AddEntityFrameworkSqlServer() .AddDbContext&lt;LogManagerContext&gt;(options =&gt; options.UseSqlServer(Configuration[&quot;Data:DefaultConnection:Connectionstring&quot;])); services.AddSingleton(c =&gt; Configuration); // Add Identity services to the services container. services.AddIdentity&lt;ApplicationUser, IdentityRole&gt;() .AddEntityFrameworkStores&lt;LogManagerContext&gt;() .AddDefaultTokenProviders(); // Add MVC services to the services container. services.AddMvc(); services.AddTransient&lt;IHttpContextAccessor, HttpContextAccessor&gt;(); //Add all SignalR related services to IoC. - Signal R not ready yet - Chad //services.AddSignalR(); //Add InMemoryCache services.AddMemoryCache(); services.AddSession(options =&gt; { options.IdleTimeout = System.TimeSpan.FromHours(1); options.CookieName = &quot;.LogManager&quot;; }); // Uncomment the following line to add Web API servcies which makes it easier to port Web API 2 controllers. // You need to add Microsoft.AspNet.Mvc.WebApiCompatShim package to project.json // services.AddWebApiConventions(); // Register application services. services.AddTransient&lt;IEmailSender, AuthMessageSender&gt;(); } // Configure is called after ConfigureServices is called. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseSession(); // Configure the HTTP request pipeline. // Add the console logger. //loggerFactory.MinimumLevel = LogLevel.Information; - moved to appsettings.json -chad loggerFactory.AddConsole(); loggerFactory.AddDebug(); loggerFactory.AddNLog(); // Add the following to the request pipeline only in development environment. if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); //app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll); } else { // Add Error handling middleware which catches all application specific errors and // sends the request to the following path or controller action. app.UseExceptionHandler(&quot;/Home/Error&quot;); } env.ConfigureNLog(&quot;NLog.config&quot;); // Add static files to the request pipeline. app.UseStaticFiles(); // Add cookie-based authentication to the request pipeline. app.UseIdentity(); //SignalR //app.UseSignalR(); // Add MVC to the request pipeline. app.UseMvc(routes =&gt; { routes.MapRoute( name: &quot;default&quot;, template: &quot;{controller}/{action}/{id?}&quot;, defaults: new { controller = &quot;Home&quot;, action = &quot;Index&quot; } ); // Uncomment the following line to add a route for porting Web API 2 controllers. // routes.MapWebApiRoute(&quot;DefaultApi&quot;, &quot;api/{controller}/{id?}&quot;); }); } </code></pre> <p>And here's the Context:</p> <pre><code>public class ApplicationUser : IdentityUser { // Add Custom Profile Fields public string Name { get; set; } } public class LogManagerContext : IdentityDbContext&lt;ApplicationUser&gt; { public DbSet&lt;LogEvent&gt; LogEvents { get; set; } public DbSet&lt;Client&gt; Clients { get; set; } public DbSet&lt;LogEventsHistory&gt; LogEventsHistory { get; set; } public DbSet&lt;LogEventsLineHistory&gt; LogEventsLineHistory { get; set; } public DbSet&lt;LogRallyHistory&gt; LogRallyHistory { get; set; } public DbSet&lt;Flag&gt; Flags { get; set; } protected override void OnModelCreating(ModelBuilder builder) { builder.Entity&lt;LogEvent&gt;().HasKey(x =&gt; x.LogId); builder.Entity&lt;LogEvent&gt;().ToTable(&quot;LogEvents&quot;); builder.Entity&lt;Client&gt;().HasKey(x =&gt; x.ClientId); builder.Entity&lt;Client&gt;().ToTable(&quot;Clients&quot;); builder.Entity&lt;LogEventsHistory&gt;().HasKey(x =&gt; x.HistoryId); builder.Entity&lt;Flag&gt;().HasKey(x =&gt; x.FlagId); builder.Entity&lt;Flag&gt;().ToTable(&quot;Flags&quot;); builder.Entity&lt;LogRallyHistory&gt;().HasKey(x =&gt; x.HistoryId); builder.Entity&lt;LogEventsLineHistory&gt;().HasKey(x =&gt; x.LineHistoryId); base.OnModelCreating(builder); } </code></pre>
38,343,528
12
0
null
2016-07-12 20:37:18.08 UTC
13
2022-08-17 20:53:27.26 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,744,254
null
1
116
c#|entity-framework|asp.net-core|asp.net-identity-3
189,314
<blockquote> <p>If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.</p> </blockquote> <p>The error message says your <code>DbContext</code>(<code>LogManagerContext</code> ) needs a constructor which accepts a <code>DbContextOptions</code>. But I couldn't find such a constructor in your <code>DbContext</code>. So adding the below constructor probably solves your problem.</p> <pre class="lang-cs prettyprint-override"><code>public LogManagerContext(DbContextOptions options) : base(options) { } </code></pre> <p><strong>Edit for comment</strong></p> <p>If you don't register <code>IHttpContextAccessor</code> explicitly, use below code:</p> <pre class="lang-cs prettyprint-override"><code>services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;(); </code></pre>
419,710
How do I pan the image inside a UIImageView?
<p>I have a <code>UIImageView</code> that is displaying an image that is wider and taller than the <code>UIImageView</code> is. I would like to pan the image within the view using an animation (so that the pan is nice and smooth).</p> <p>It seems to me that I should be able to just adjust the <code>bounds.origin</code> of the <code>UIImageView</code>, and the image should move (because the image should paint inside the view with that as <strong>its</strong> origin, right?) but that doesn't seem to work. The <code>bounds.origin</code> changes, but the image draws in the same location.</p> <p>What almost works is to change the <code>contentsRect</code> of the view's layer. But this begins as a unit square, even though the viewable area of the image is not the whole image. So I'm not sure how I would detect that the far edge of the image is being pulled into the viewable area (which I need to avoid, since it displays by stretching the edge out to infinity, which looks, well, sub-par).</p> <p>My view currently has its <code>contentsGravity</code> set to <code>kCAGravityTopLeft</code> via Interface Builder, if that makes a difference (Is it causing the image to move?). No other options seemed to be any better, though.</p> <p>UPDATE: to be clear, I want to move the image <strong>inside</strong> the view, while keeping the view in the same spot.</p>
423,405
2
0
null
2009-01-07 09:29:28.793 UTC
17
2015-02-06 12:25:23.003 UTC
2009-01-07 16:39:28.533 UTC
Chris Hanson
714
TALlama
5,657
null
1
26
cocoa-touch|core-animation
45,869
<p>Brad Larson pointed me down the right road with his suggestion to put the <code>UIImageView</code> inside a <code>UIScrollView</code>.</p> <p>In the end I put the <code>UIImageView</code> inside of a <code>UIScrollView</code>, and set the scrollView's <code>contentSize</code> <strong>and</strong> the <code>imageView</code>'s bounds to be the same size as the image in the UIImage:</p> <pre><code>UIImage* image = imageView.image; imageView.bounds = CGRectMake(0, 0, image.size.width, image.size.height); scrollView.contentSize = image.size; </code></pre> <p>Then, I can animate the scrollView's <code>contentOffset</code> to achieve a nice panning effect:</p> <pre><code>[UIView beginAnimations:@"pan" context:nil]; [UIView setAnimationDuration:animationDuration]; scrollView.contentOffset = newRect.origin; [UIView commitAnimations]; </code></pre> <p>In my particular case, I'm panning to a random space in the image. In order to find a proper rect to pan <strong>to</strong> and a proper duration to get a nice constant speed, I use the following:</p> <pre><code>UIImage* image = imageView.image; float xNewOrigin = [TCBRandom randomIntLessThan:image.size.width - scrollView.bounds.size.width]; float yNewOrigin = [TCBRandom randomIntLessThan:image.size.height - scrollView.bounds.size.height]; CGRect oldRect = scrollView.bounds; CGRect newRect = CGRectMake( xNewOrigin, yNewOrigin, scrollView.bounds.size.width, scrollView.bounds.size.height); float xDistance = fabs(xNewOrigin - oldRect.origin.x); float yDistance = fabs(yNewOrigin - oldRect.origin.y); float hDistance = sqrtf(powf(xDistance, 2) + powf(yDistance, 2)); float hDistanceInPixels = hDistance; float animationDuration = hDistanceInPixels / speedInPixelsPerSecond; </code></pre> <p>I'm using a <code>speedInPixelsPerSecond</code> of <code>10.0f</code>, but other applications might want to use a different value.</p>
1,115,834
How do I use an extension method in an ASP.NET MVC View?
<p>How do I access an extension method in an ASP.Net MVC View? In C# I do</p> <pre><code>using MyProject.Extensions; </code></pre> <p>and I remember seeing an XML equivalent to put in a view, but I can't find it anymore.</p>
1,115,842
2
3
null
2009-07-12 11:14:33.8 UTC
5
2012-10-08 20:38:49.757 UTC
2009-07-12 12:48:07.157 UTC
null
80,601
null
6,068
null
1
36
asp.net-mvc|views|extension-methods
17,153
<p>In View:</p> <pre><code>&lt;%@ Import Namespace="MyProject.Extensions" %&gt; </code></pre> <p>Or in web.config (for all Views):</p> <pre><code>&lt;pages&gt; &lt;namespaces&gt; &lt;add namespace="System.Web.Mvc" /&gt; &lt;add namespace="System.Web.Mvc.Ajax" /&gt; &lt;add namespace="System.Web.Mvc.Html" /&gt; &lt;add namespace="System.Web.Routing" /&gt; &lt;add namespace="System.Linq" /&gt; &lt;add namespace="System.Collections.Generic" /&gt; &lt;add namespace="MyProject.Extensions" /&gt; &lt;/namespaces&gt; &lt;/pages&gt; </code></pre>
2,591,995
How do I use Perl's localtime with print to get the timestamp?
<p>I have used the following statements to get the current time.</p> <pre><code> print "$query executed successfully at ",localtime; print "$query executed successfully at ",(localtime); print "$query executed successfully at ".(localtime); </code></pre> <p><strong>Output</strong><br><br></p> <pre><code> executed successfully at 355516731103960 executed successfully at 355516731103960 executed successfully at Wed Apr 7 16:55:35 2010 </code></pre> <p>The first two statements are not printing the current time in a date format. Third statement only giving the correct output in a date format.</p> <p>My understanding is the first one is returning a value in scalar context, so it is returning numbers.</p> <p>Then in the second print I used localtime in list context only, why it's also giving number output.</p>
2,592,984
5
0
null
2010-04-07 11:31:36.833 UTC
null
2015-12-14 22:24:04.397 UTC
2015-12-14 22:24:04.397 UTC
null
244,297
null
288,575
null
1
23
perl|built-in
59,122
<p>Perhaps the most important thing you can learn for programming in Perl, is context. Many built-in subroutines, and operators, behave differently depending on the context.</p> <pre><code>print "$query executed successfully at ", localtime, "\n"; # list context print "$query executed successfully at ",(localtime),"\n"; # list context print "$query executed successfully at ". localtime, "\n"; # scalar context print "$query executed successfully at ".(localtime),"\n"; # scalar context print "$query executed successfully at ", scalar localtime, "\n"; # scalar context print "$query executed successfully at ", scalar (localtime),"\n"; # scalar context </code></pre> <p>This can be made clearer by splitting up the statements.</p> <pre><code>my $time = localtime; # scalar context print "$query executed successfully at $time\n"; my @time = localtime; # list context print "$query executed successfully at @time\n"; </code></pre>
2,989,550
How do I access Dictionary items?
<p>I am developing a C# VS2008 / SQL Server website app and am new to the Dictionary class. Can you please advise on best method of accomplishing this? Here is a code snippet:</p> <pre><code>SqlConnection conn2 = new SqlConnection(connString); SqlCommand cmd = conn2.CreateCommand(); cmd.CommandText = "dbo.AppendDataCT"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = conn2; SqlParameter p1, p2, p3; foreach (string s in dt.Rows[1].ItemArray) { DataRow dr = dt.Rows[1]; // second row p1 = cmd.Parameters.AddWithValue((string)dic[0], (string)dr[0]); p1.SqlDbType = SqlDbType.VarChar; p2 = cmd.Parameters.AddWithValue((string)dic[1], (string)dr[1]); p2.SqlDbType = SqlDbType.VarChar; p3 = cmd.Parameters.AddWithValue((string)dic[2], (string)dr[2]); p3.SqlDbType = SqlDbType.VarChar; } </code></pre> <p>but this is giving me compiler error:</p> <pre><code>The best overloaded method match for 'System.Collections.Generic.Dictionary&lt;string,string&gt;.this[string]' has some invalid arguments </code></pre> <p>I just want to access each value from "dic" and load into these SQL parameters. How do I do this? Do I have to enter the key? The keys are named "col1", "col2", etc., so not the most user-friendly. Any other tips? Thanks!</p>
2,989,593
6
2
null
2010-06-07 12:44:06.527 UTC
2
2018-02-15 08:59:32.73 UTC
2016-12-29 19:31:08.603 UTC
null
736,079
null
123,348
null
1
14
c#|dictionary|visual-studio-2008
56,936
<p>You seem to be trying to access a <code>Dictionary&lt;string, string&gt;</code> by <em>integer</em> index. You can't do that - you have to look up the value by the key, which is a string.</p> <p>If you don't want to use string keys, why are you using a <code>Dictionary&lt;string, string&gt;</code> to start with? Could you either use a <code>List&lt;string&gt;</code> or a <code>Dictionary&lt;int, string&gt;</code>?</p> <p>Note that once you <em>have</em> managed to use the indexer appropriately, you won't need to cast to string.</p>
2,695,837
Rails: convert UTC DateTime to another time zone
<p>In Ruby/Rails, how do I convert a UTC DateTime to another time zone?</p>
2,695,858
6
0
null
2010-04-23 02:33:20.353 UTC
44
2018-09-21 21:42:31.26 UTC
2013-11-30 11:01:21.543 UTC
null
558,639
null
57,643
null
1
122
ruby-on-rails|ruby|datetime|runtime
96,687
<pre><code>time.in_time_zone(time_zone) </code></pre> <p>Example:</p> <pre><code>zone = ActiveSupport::TimeZone.new("Central Time (US &amp; Canada)") Time.now.in_time_zone(zone) </code></pre> <p>or just</p> <pre><code>Time.now.in_time_zone("Central Time (US &amp; Canada)") </code></pre> <p>You can find the names of the ActiveSupport time zones by doing:</p> <pre><code>ActiveSupport::TimeZone.all.map(&amp;:name) # or for just US ActiveSupport::TimeZone.us_zones.map(&amp;:name) </code></pre>
2,919,367
Get values from *.resx files in XAML
<p>Is it possible to add some value from resource file right into the XAML markup? Or for localization we always have to make something like this in *.cs file:</p> <pre><code>txtMessage.Text = Messages.WarningUserMessage; </code></pre> <p>Where <code>Messages</code> is resource, and <code>txtMessage</code> is TextBlock.</p>
2,919,391
7
3
null
2010-05-27 07:57:36.667 UTC
20
2018-09-27 08:53:24.417 UTC
null
null
null
null
47,672
null
1
76
c#|xaml|localization|resx
86,829
<p>Make sure that Code Generation is set to Public in the resx editor, then you can simply use:</p> <pre><code>&lt;TextBlock Text="{x:Static Messages.WarningUserMessage}" /&gt; </code></pre>
2,343,789
C# XNA: Optimizing Collision Detection?
<p>I'm working on a simple demo for collision detection, which contains only a bunch of objects bouncing around in the window. (The goal is to see how many objects the game can handle at once without dropping frames.)</p> <p>There is gravity, so the objects are either moving or else colliding with a wall.</p> <p>The naive solution was O(n^2): </p> <pre><code>foreach Collidable c1: foreach Collidable c2: checkCollision(c1, c2); </code></pre> <p>This is pretty bad. So I set up <code>CollisionCell</code> objects, which maintain information about a portion of the screen. The idea is that each <code>Collidable</code> only needs to check for the other objects in its cell. With 60 px by 60 px cells, this yields almost a 10x improvement, but I'd like to push it further.</p> <p>A profiler has revealed that the the code spends 50% of its time in the function each cell uses to get its contents. Here it is:</p> <pre><code> // all the objects in this cell public ICollection&lt;GameObject&gt; Containing { get { ICollection&lt;GameObject&gt; containing = new HashSet&lt;GameObject&gt;(); foreach (GameObject obj in engine.GameObjects) { // 20% of processor time spent in this conditional if (obj.Position.X &gt;= bounds.X &amp;&amp; obj.Position.X &lt; bounds.X + bounds.Width &amp;&amp; obj.Position.Y &gt;= bounds.Y &amp;&amp; obj.Position.Y &lt; bounds.Y + bounds.Height) { containing.Add(obj); } } return containing; } } </code></pre> <p>Of that 20% of the program's time is spent in that conditional.</p> <p>Here is where the above function gets called:</p> <pre><code> // Get a list of lists of cell contents List&lt;List&lt;GameObject&gt;&gt; cellContentsSet = cellManager.getCellContents(); // foreach item, only check items in the same cell foreach (List&lt;GameObject&gt; cellMembers in cellContentsSet) { foreach (GameObject item in cellMembers) { // process collisions } } //... // Gets a list of list of cell contents (each sub list = 1 cell) internal List&lt;List&lt;GameObject&gt;&gt; getCellContents() { List&lt;List&lt;GameObject&gt;&gt; result = new List&lt;List&lt;GameObject&gt;&gt;(); foreach (CollisionCell cell in cellSet) { result.Add(new List&lt;GameObject&gt;(cell.Containing.ToArray())); } return result; } </code></pre> <p>Right now, I have to iterate over every cell - even empty ones. Perhaps this could be improved on somehow, but I'm not sure how to verify that a cell is empty without looking at it somehow. (Maybe I could implement something like sleeping objects, in some physics engines, where if an object will be still for a while it goes to sleep and is not included in calculations for every frame.)</p> <p>What can I do to optimize this? (Also, I'm new to C# - are there any other glaring stylistic errors?)</p> <p>When the game starts lagging out, the objects tend to be packed fairly tightly, so there's not that much motion going on. Perhaps I can take advantage of this somehow, writing a function to see if, given an object's current velocity, it can possibly leave its current cell before the next call to <code>Update()</code></p> <p><strong>UPDATE 1</strong> I decided to maintain a list of the objects that were found to be in the cell at last update, and check those first to see if they were still in the cell. Also, I maintained an <code>area</code> of the <code>CollisionCell</code> variable, when when the cell was filled I could stop looking. Here is my implementation of that, and it made the whole demo much slower:</p> <pre><code> // all the objects in this cell private ICollection&lt;GameObject&gt; prevContaining; private ICollection&lt;GameObject&gt; containing; internal ICollection&lt;GameObject&gt; Containing { get { return containing; } } /** * To ensure that `containing` and `prevContaining` are up to date, this MUST be called once per Update() loop in which it is used. * What is a good way to enforce this? */ public void updateContaining() { ICollection&lt;GameObject&gt; result = new HashSet&lt;GameObject&gt;(); uint area = checked((uint) bounds.Width * (uint) bounds.Height); // the area of this cell // first, try to fill up this cell with objects that were in it previously ICollection&lt;GameObject&gt;[] toSearch = new ICollection&lt;GameObject&gt;[] { prevContaining, engine.GameObjects }; foreach (ICollection&lt;GameObject&gt; potentiallyContained in toSearch) { if (area &gt; 0) { // redundant, but faster? foreach (GameObject obj in potentiallyContained) { if (obj.Position.X &gt;= bounds.X &amp;&amp; obj.Position.X &lt; bounds.X + bounds.Width &amp;&amp; obj.Position.Y &gt;= bounds.Y &amp;&amp; obj.Position.Y &lt; bounds.Y + bounds.Height) { result.Add(obj); area -= checked((uint) Math.Pow(obj.Radius, 2)); // assuming objects are square if (area &lt;= 0) { break; } } } } } prevContaining = containing; containing = result; } </code></pre> <p><strong>UPDATE 2</strong> I abandoned that last approach. Now I'm trying to maintain a pool of collidables (<code>orphans</code>), and remove objects from them when I find a cell that contains them:</p> <pre><code> internal List&lt;List&lt;GameObject&gt;&gt; getCellContents() { List&lt;GameObject&gt; orphans = new List&lt;GameObject&gt;(engine.GameObjects); List&lt;List&lt;GameObject&gt;&gt; result = new List&lt;List&lt;GameObject&gt;&gt;(); foreach (CollisionCell cell in cellSet) { cell.updateContaining(ref orphans); // this call will alter orphans! result.Add(new List&lt;GameObject&gt;(cell.Containing)); if (orphans.Count == 0) { break; } } return result; } // `orphans` is a list of GameObjects that do not yet have a cell public void updateContaining(ref List&lt;GameObject&gt; orphans) { ICollection&lt;GameObject&gt; result = new HashSet&lt;GameObject&gt;(); for (int i = 0; i &lt; orphans.Count; i++) { // 20% of processor time spent in this conditional if (orphans[i].Position.X &gt;= bounds.X &amp;&amp; orphans[i].Position.X &lt; bounds.X + bounds.Width &amp;&amp; orphans[i].Position.Y &gt;= bounds.Y &amp;&amp; orphans[i].Position.Y &lt; bounds.Y + bounds.Height) { result.Add(orphans[i]); orphans.RemoveAt(i); } } containing = result; } </code></pre> <p>This only yields a marginal improvement, not the 2x or 3x I'm looking for.</p> <p><strong>UPDATE 3</strong> Again I abandoned the above approaches, and decided to let each object maintain its current cell:</p> <pre><code> private CollisionCell currCell; internal CollisionCell CurrCell { get { return currCell; } set { currCell = value; } } </code></pre> <p>This value gets updated:</p> <pre><code> // Run 1 cycle of this object public virtual void Run() { position += velocity; parent.CellManager.updateContainingCell(this); } </code></pre> <p>CellManager code:</p> <pre><code>private IDictionary&lt;Vector2, CollisionCell&gt; cellCoords = new Dictionary&lt;Vector2, CollisionCell&gt;(); internal void updateContainingCell(GameObject gameObject) { CollisionCell currCell = findContainingCell(gameObject); gameObject.CurrCell = currCell; if (currCell != null) { currCell.Containing.Add(gameObject); } } // null if no such cell exists private CollisionCell findContainingCell(GameObject gameObject) { if (gameObject.Position.X &gt; GameEngine.GameWidth || gameObject.Position.X &lt; 0 || gameObject.Position.Y &gt; GameEngine.GameHeight || gameObject.Position.Y &lt; 0) { return null; } // we'll need to be able to access these outside of the loops uint minWidth = 0; uint minHeight = 0; for (minWidth = 0; minWidth + cellWidth &lt; gameObject.Position.X; minWidth += cellWidth) ; for (minHeight = 0; minHeight + cellHeight &lt; gameObject.Position.Y; minHeight += cellHeight) ; CollisionCell currCell = cellCoords[new Vector2(minWidth, minHeight)]; // Make sure `currCell` actually contains gameObject Debug.Assert(gameObject.Position.X &gt;= currCell.Bounds.X &amp;&amp; gameObject.Position.X &lt;= currCell.Bounds.Width + currCell.Bounds.X, String.Format("{0} should be between lower bound {1} and upper bound {2}", gameObject.Position.X, currCell.Bounds.X, currCell.Bounds.X + currCell.Bounds.Width)); Debug.Assert(gameObject.Position.Y &gt;= currCell.Bounds.Y &amp;&amp; gameObject.Position.Y &lt;= currCell.Bounds.Height + currCell.Bounds.Y, String.Format("{0} should be between lower bound {1} and upper bound {2}", gameObject.Position.Y, currCell.Bounds.Y, currCell.Bounds.Y + currCell.Bounds.Height)); return currCell; } </code></pre> <p>I thought this would make it better - now I only have to iterate over collidables, not all collidables * cells. Instead, the game is now hideously slow, delivering only 1/10th of its performance with my above approaches.</p> <p>The profiler indicates that a different method is now the main hot spot, and the time to get neighbors for an object is trivially short. That method didn't change from before, so perhaps I'm calling it WAY more than I used to...</p>
2,343,949
8
3
null
2010-02-26 18:11:59.383 UTC
16
2018-10-14 03:16:34.11 UTC
2018-10-14 03:16:34.11 UTC
null
2,370,483
null
147,601
null
1
15
c#|optimization|xna
9,436
<p>It spends 50% of its time in that function because you call that function a lot. Optimizing that one function will only yield incremental improvements to performance.</p> <p>Alternatively, just call the function less!</p> <p>You've already started down that path by setting up a spatial partitioning scheme (lookup <a href="http://en.wikipedia.org/wiki/Quadtree" rel="noreferrer">Quadtrees</a> to see a more advanced form of your technique).</p> <p>A second approach is to break your N*N loop into an incremental form and to use <strong>a CPU budget</strong>.</p> <p>You can allocate a CPU budget for each of the modules that want action during frame times (during Updates). Collision is one of these modules, AI might be another. </p> <p>Let's say you want to run your game at 60 fps. This means you have about 1/60 s = 0.0167 s of CPU time to burn between frames. No we can split those 0.0167 s between our modules. Let's give <strong>collision</strong> 30% of the budget: <strong>0.005 s</strong>.</p> <p>Now your collision algorithm knows that it can only spend 0.005 s working. So if it runs out of time, it will need to postpone some tasks for later - you will make the algorithm incremental. Code for achieving this can be as simple as:</p> <pre><code>const double CollisionBudget = 0.005; Collision[] _allPossibleCollisions; int _lastCheckedCollision; void HandleCollisions() { var startTime = HighPerformanceCounter.Now; if (_allPossibleCollisions == null || _lastCheckedCollision &gt;= _allPossibleCollisions.Length) { // Start a new series _allPossibleCollisions = GenerateAllPossibleCollisions(); _lastCheckedCollision = 0; } for (var i=_lastCheckedCollision; i&lt;_allPossibleCollisions.Length; i++) { // Don't go over the budget if (HighPerformanceCount.Now - startTime &gt; CollisionBudget) { break; } _lastCheckedCollision = i; if (CheckCollision(_allPossibleCollisions[i])) { HandleCollision(_allPossibleCollisions[i]); } } } </code></pre> <p>There, now it doesn't matter how fast the collision code is, it will be done as quickly as is possible <strong>without affecting the user's perceived performance</strong>. </p> <p>Benefits include:</p> <ul> <li>The algorithm is designed to run out of time, it just resumes on the next frame, so you don't have to worry about this particular edge case.</li> <li>CPU budgeting becomes more and more important as the number of advanced/time consuming algorithms increases. Think AI. So it's a good idea to implement such a system early on.</li> <li>Human response time is less than 30 Hz, your frame loop is running at 60 Hz. That gives the algorithm 30 frames to complete its work, so it's OK that it doesn't finish its work.</li> <li>Doing it this way gives <strong>stable</strong>, <strong>data-independent</strong> frame rates. </li> <li>It still benefits from performance optimizations to the collision algorithm itself.</li> <li>Collision algorithms are designed to track down the "sub frame" in which collisions happened. That is, <em>you will never</em> be so lucky as to catch a collision <em>just</em> as it happens - thinking you're doing so is lying to yourself. </li> </ul>
3,144,050
Use CSS to make a span not clickable
<pre><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;a href="http://www.google.com"&gt; &lt;span&gt;title&lt;br&gt;&lt;/span&gt; &lt;span&gt;description&lt;br&gt;&lt;/span&gt; &lt;span&gt;some url&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I am pretty new to CSS, I have a simple case like the above. I would like to make the "title" and "some url" clickable but want to make description as non-clickable. Is there any way to do that by applying some CSS on the span so that whatever inside that span, it is not clickable. My constraint is that, I do not want to change the structure of the div, instead just applying css can we make a span which is inside an anchor tag, not clickable ? </p>
3,144,139
8
4
null
2010-06-29 19:31:36.233 UTC
15
2022-06-11 00:49:29.373 UTC
2018-10-01 09:01:22.173 UTC
null
7,070,094
null
61,395
null
1
97
css
262,575
<p>Using CSS you cannot, CSS will only change the appearance of the span. However you can do it without changing the structure of the div by adding an onclick handler to the span:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;a href="http://www.google.com"&gt; &lt;span&gt;title&lt;br&gt;&lt;/span&gt; &lt;span onclick='return false;'&gt;description&lt;br&gt;&lt;/span&gt; &lt;span&gt;some url&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>You can then style it so that it looks un-clickable too:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;style type='text/css'&gt; a span.unclickable { text-decoration: none; } a span.unclickable:hover { cursor: default; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;a href="http://www.google.com"&gt; &lt;span&gt;title&lt;br&gt;&lt;/span&gt; &lt;span class='unclickable' onclick='return false;'&gt;description&lt;br&gt;&lt;/span&gt; &lt;span&gt;some url&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
2,358,214
In Rails, how do you functional test a Javascript response format?
<p>If your controller action looks like this:</p> <pre><code>respond_to do |format| format.html { raise 'Unsupported' } format.js # index.js.erb end </code></pre> <p>and your functional test looks like this:</p> <pre><code>test "javascript response..." do get :index end </code></pre> <p>it will execute the HTML branch of the respond_to block.</p> <p>If you try this:</p> <pre><code>test "javascript response..." do get 'index.js' end </code></pre> <p>it executes the view (index.js.erb) withOUT running the controller action!</p>
2,358,489
9
0
null
2010-03-01 18:49:23.75 UTC
10
2019-06-19 06:31:14.183 UTC
null
null
null
null
4,061
null
1
35
javascript|ruby-on-rails|response|functional-testing
16,163
<p>Pass in a <code>:format</code> with your normal params to trigger a response in that format.</p> <pre><code>get :index, :format =&gt; 'js' </code></pre> <p>No need to mess with your request headers.</p>
2,946,954
Make ListView.ScrollIntoView Scroll the Item into the Center of the ListView (C#)
<p><code>ListView.ScrollIntoView(object)</code> currently finds an object in the <code>ListView</code> and scrolls to it. If you are positioned beneath the object you are scrolling to, it scrolls the object to the top row. If you are positioned above, it scrolls it into view at the bottom row.</p> <p>I'd like to have the item be scrolled right into the center of my list view if it is currently not visible. Is there an easy way to accomplish this?</p>
3,002,013
10
0
null
2010-06-01 02:18:49.063 UTC
22
2022-09-20 05:36:04.237 UTC
2012-12-27 10:34:14.23 UTC
null
45,382
null
102,635
null
1
54
c#|wpf|visual-studio|listview
52,433
<p>It is very easy to do this in WPF with an extension method I wrote. All you have to do to scroll an item to the center of the view is to call a single method.</p> <p>Suppose you have this XAML:</p> <pre><code>&lt;ListView x:Name="view" ItemsSource="{Binding Data}" /&gt; &lt;ComboBox x:Name="box" ItemsSource="{Binding Data}" SelectionChanged="ScrollIntoView" /&gt; </code></pre> <p>Your ScrollIntoView method will be simply:</p> <pre><code>private void ScrollIntoView(object sender, SelectionChangedEventArgs e) { view.ScrollToCenterOfView(box.SelectedItem); } </code></pre> <p>Obviously this could be done using a ViewModel as well rather than referencing the controls explicitly.</p> <p>Following is the implementation. It is very general, handling all the IScrollInfo possibilities. It works with ListBox or any other ItemsControl, and works with any panel including StackPanel, VirtualizingStackPanel, WrapPanel, DockPanel, Canvas, Grid, etc.</p> <p>Just put this in a .cs file somewhere in your project:</p> <pre><code>public static class ItemsControlExtensions { public static void ScrollToCenterOfView(this ItemsControl itemsControl, object item) { // Scroll immediately if possible if(!itemsControl.TryScrollToCenterOfView(item)) { // Otherwise wait until everything is loaded, then scroll if(itemsControl is ListBox) ((ListBox)itemsControl).ScrollIntoView(item); itemsControl.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() =&gt; { itemsControl.TryScrollToCenterOfView(item); })); } } private static bool TryScrollToCenterOfView(this ItemsControl itemsControl, object item) { // Find the container var container = itemsControl.ItemContainerGenerator.ContainerFromItem(item) as UIElement; if(container==null) return false; // Find the ScrollContentPresenter ScrollContentPresenter presenter = null; for(Visual vis = container; vis!=null &amp;&amp; vis!=itemsControl; vis = VisualTreeHelper.GetParent(vis) as Visual) if((presenter = vis as ScrollContentPresenter)!=null) break; if(presenter==null) return false; // Find the IScrollInfo var scrollInfo = !presenter.CanContentScroll ? presenter : presenter.Content as IScrollInfo ?? FirstVisualChild(presenter.Content as ItemsPresenter) as IScrollInfo ?? presenter; // Compute the center point of the container relative to the scrollInfo Size size = container.RenderSize; Point center = container.TransformToAncestor((Visual)scrollInfo).Transform(new Point(size.Width/2, size.Height/2)); center.Y += scrollInfo.VerticalOffset; center.X += scrollInfo.HorizontalOffset; // Adjust for logical scrolling if(scrollInfo is StackPanel || scrollInfo is VirtualizingStackPanel) { double logicalCenter = itemsControl.ItemContainerGenerator.IndexFromContainer(container) + 0.5; Orientation orientation = scrollInfo is StackPanel ? ((StackPanel)scrollInfo).Orientation : ((VirtualizingStackPanel)scrollInfo).Orientation; if(orientation==Orientation.Horizontal) center.X = logicalCenter; else center.Y = logicalCenter; } // Scroll the center of the container to the center of the viewport if(scrollInfo.CanVerticallyScroll) scrollInfo.SetVerticalOffset(CenteringOffset(center.Y, scrollInfo.ViewportHeight, scrollInfo.ExtentHeight)); if(scrollInfo.CanHorizontallyScroll) scrollInfo.SetHorizontalOffset(CenteringOffset(center.X, scrollInfo.ViewportWidth, scrollInfo.ExtentWidth)); return true; } private static double CenteringOffset(double center, double viewport, double extent) { return Math.Min(extent - viewport, Math.Max(0, center - viewport/2)); } private static DependencyObject FirstVisualChild(Visual visual) { if(visual==null) return null; if(VisualTreeHelper.GetChildrenCount(visual)==0) return null; return VisualTreeHelper.GetChild(visual, 0); } } </code></pre>
2,562,051
ListView item background via custom selector
<p>Is it possible to apply a custom background to each Listview item via the list selector?</p> <p>The default selector specifies <code>@android:color/transparent</code> for the <code>state_focused="false"</code> case, but changing this to some custom drawable doesn't affect items that aren't selected. Romain Guy seems to suggest <a href="https://stackoverflow.com/questions/2217753/changing-background-color-of-listview-items-on-android/2218270#2218270">in this answer</a> that this is possible.</p> <p>I'm currently achieving the same affect by using a custom background on each view and hiding it when the item is selected/focused/whatever so the selector is shown, but it'd be more elegant to have this all defined in one place.</p> <p>For reference, this is the selector I'm using to try and get this working:</p> <pre><code>&lt;selector xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item android:state_focused="false" android:drawable="@drawable/list_item_gradient" /&gt; &lt;!-- Even though these two point to the same resource, have two states so the drawable will invalidate itself when coming out of pressed state. --&gt; &lt;item android:state_focused="true" android:state_enabled="false" android:state_pressed="true" android:drawable="@drawable/list_selector_background_disabled" /&gt; &lt;item android:state_focused="true" android:state_enabled="false" android:drawable="@drawable/list_selector_background_disabled" /&gt; &lt;item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/list_selector_background_transition" /&gt; &lt;item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/list_selector_background_transition" /&gt; &lt;item android:state_focused="true" android:drawable="@drawable/list_selector_background_focus" /&gt; &lt;/selector&gt; </code></pre> <p>And this is how I'm setting the selector:</p> <pre><code>&lt;ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:listSelector="@drawable/list_selector_background" /&gt; </code></pre> <p>Thanks in advance for any help!</p>
2,830,994
10
0
null
2010-04-01 16:44:42.413 UTC
87
2016-09-27 13:08:00.233 UTC
2017-05-23 12:26:29.837 UTC
null
-1
null
307,071
null
1
98
android|listview
155,016
<p>I've been frustrated by this myself and finally solved it. As Romain Guy hinted to, there's another state, <code>"android:state_selected"</code>, that you must use. Use a state drawable for the background of your list item, and use a different state drawable for <code>listSelector</code> of your list:</p> <p>list_row_layout.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="?android:attr/listPreferredItemHeight" android:background="@drawable/listitem_background" &gt; ... &lt;/LinearLayout&gt; </code></pre> <p>listitem_background.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;selector xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item android:state_selected="true" android:drawable="@color/android:transparent" /&gt; &lt;item android:drawable="@drawable/listitem_normal" /&gt; &lt;/selector&gt; </code></pre> <p>layout.xml that includes the ListView:</p> <pre><code>... &lt;ListView android:layout_width="fill_parent" android:layout_height="wrap_content" android:listSelector="@drawable/listitem_selector" /&gt; ... </code></pre> <p>listitem_selector.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;selector xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item android:state_pressed="true" android:drawable="@drawable/listitem_pressed" /&gt; &lt;item android:state_focused="true" android:drawable="@drawable/listitem_selected" /&gt; &lt;/selector&gt; </code></pre>
2,762,093
Java Compare Two Lists
<p>I have two lists ( not java lists, you can say two columns)</p> <p>For example</p> <pre><code>**List 1** **Lists 2** milan hafil dingo iga iga dingo elpha binga hafil mike meat dingo milan elpha meat iga neeta.peeta </code></pre> <p>I'd like a method that returns how many elements are same. For this example it should be 3 and it should return me similar values of both list and different values too.</p> <p>Should I use hashmap if yes then what method to get my result? </p> <p>Please help</p> <p>P.S: It is not a school assignment :) So if you just guide me it will be enough</p>
2,762,137
10
5
null
2010-05-04 00:34:47.973 UTC
42
2019-07-19 17:17:43.313 UTC
2010-05-04 00:53:03.487 UTC
null
238,384
null
238,384
null
1
107
java|list|comparison|hashmap
439,440
<p><strong>EDIT</strong></p> <p>Here are two versions. One using <code>ArrayList</code> and other using <code>HashSet</code> </p> <p>Compare them and create your <strong>own</strong> version from this, until you get what you need. </p> <p>This should be enough to cover the:</p> <blockquote> <p><em>P.S: It is not a school assignment :) So if you just guide me it will be enough</em></p> </blockquote> <p>part of your question.</p> <p><strong>continuing with the original answer:</strong> </p> <p>You may use a <code>java.util.Collection</code> and/or <code>java.util.ArrayList</code> for that. </p> <p>The <a href="http://java.sun.com/javase/6/docs/api/java/util/Collection.html#retainAll%28java.util.Collection%29" rel="noreferrer">retainAll</a> method does the following:</p> <blockquote> <p><em>Retains only the elements in this collection that are contained in the specified collection</em></p> </blockquote> <p>see this sample:</p> <pre><code>import java.util.Collection; import java.util.ArrayList; import java.util.Arrays; public class Repeated { public static void main( String [] args ) { Collection listOne = new ArrayList(Arrays.asList("milan","dingo", "elpha", "hafil", "meat", "iga", "neeta.peeta")); Collection listTwo = new ArrayList(Arrays.asList("hafil", "iga", "binga", "mike", "dingo")); listOne.retainAll( listTwo ); System.out.println( listOne ); } } </code></pre> <p><strong>EDIT</strong></p> <p>For the second part ( similar values ) you may use the <a href="http://java.sun.com/javase/6/docs/api/java/util/Collection.html#removeAll%28java.util.Collection%29" rel="noreferrer">removeAll</a> method:</p> <blockquote> <p><em>Removes all of this collection's elements that are also contained in the specified collection.</em></p> </blockquote> <p>This second version gives you also the similar values and handles repeated ( by discarding them).</p> <p>This time the <code>Collection</code> could be a <code>Set</code> instead of a <code>List</code> ( the difference is, the Set doesn't allow repeated values ) </p> <pre><code>import java.util.Collection; import java.util.HashSet; import java.util.Arrays; class Repeated { public static void main( String [] args ) { Collection&lt;String&gt; listOne = Arrays.asList("milan","iga", "dingo","iga", "elpha","iga", "hafil","iga", "meat","iga", "neeta.peeta","iga"); Collection&lt;String&gt; listTwo = Arrays.asList("hafil", "iga", "binga", "mike", "dingo","dingo","dingo"); Collection&lt;String&gt; similar = new HashSet&lt;String&gt;( listOne ); Collection&lt;String&gt; different = new HashSet&lt;String&gt;(); different.addAll( listOne ); different.addAll( listTwo ); similar.retainAll( listTwo ); different.removeAll( similar ); System.out.printf("One:%s%nTwo:%s%nSimilar:%s%nDifferent:%s%n", listOne, listTwo, similar, different); } } </code></pre> <p>Output:</p> <pre><code>$ java Repeated One:[milan, iga, dingo, iga, elpha, iga, hafil, iga, meat, iga, neeta.peeta, iga] Two:[hafil, iga, binga, mike, dingo, dingo, dingo] Similar:[dingo, iga, hafil] Different:[mike, binga, milan, meat, elpha, neeta.peeta] </code></pre> <p>If it doesn't do exactly what you need, it gives you a good start so you can handle from here. </p> <p>Question for the reader: How would you include all the repeated values?</p>
2,592,501
How to compare dates in Java?
<p>How do I compare dates in between in Java? </p> <p>Example:</p> <p>date1 is <code>22-02-2010</code><br /> date2 is <code>07-04-2010</code> today <br /> date3 is <code>25-12-2010</code></p> <p><code>date3</code> is always greater than <code>date1</code> and <code>date2</code> is always today. How do I verify if today's date is in between date1 and date 3?</p>
2,592,513
11
0
null
2010-04-07 12:48:36.153 UTC
91
2020-10-22 16:32:30.807 UTC
2014-07-21 10:10:12.83 UTC
null
3,375,858
null
169,277
null
1
432
java|date|comparison
1,113,964
<p><a href="http://java.sun.com/javase/6/docs/api/java/util/Date.html" rel="noreferrer">Date</a> has <a href="http://java.sun.com/javase/6/docs/api/java/util/Date.html#before(java.util.Date)" rel="noreferrer">before</a> and <a href="http://java.sun.com/javase/6/docs/api/java/util/Date.html#after(java.util.Date)" rel="noreferrer">after</a> methods and can be <a href="http://java.sun.com/javase/6/docs/api/java/util/Date.html#compareTo(java.util.Date)" rel="noreferrer">compared to each other</a> as follows:</p> <pre><code>if(todayDate.after(historyDate) &amp;&amp; todayDate.before(futureDate)) { // In between } </code></pre> <p>For an inclusive comparison:</p> <pre><code>if(!historyDate.after(todayDate) &amp;&amp; !futureDate.before(todayDate)) { /* historyDate &lt;= todayDate &lt;= futureDate */ } </code></pre> <p>You could also give <a href="http://www.joda.org/joda-time/" rel="noreferrer">Joda-Time</a> a go, but note that:</p> <blockquote> <p>Joda-Time is the <em>de facto</em> standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to <a href="https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html" rel="noreferrer">java.time</a> (<a href="https://jcp.org/en/jsr/detail?id=310" rel="noreferrer">JSR-310</a>).</p> </blockquote> <p>Back-ports are available for Java 6 and 7 as well as Android.</p>
2,467,751
Quicksort vs heapsort
<p>Both quicksort and heapsort do in-place sorting. Which is better? What are the applications and cases in which either is preferred?</p>
2,467,760
12
1
null
2010-03-18 05:45:44.31 UTC
49
2020-09-19 11:07:54.65 UTC
2010-03-24 18:47:52.24 UTC
null
164,901
null
169,210
null
1
114
algorithm|sorting|quicksort|heapsort
99,676
<p><a href="https://web.archive.org/web/20130801175915/http://www.cs.auckland.ac.nz/~jmor159/PLDS210/qsort3.html" rel="noreferrer">This paper</a> has some analysis.</p> <p>Also, from Wikipedia:</p> <blockquote> <p>The most direct competitor of quicksort is heapsort. Heapsort is typically somewhat slower than quicksort, but the worst-case running time is always Θ(nlogn). Quicksort is usually faster, though there remains the chance of worst case performance except in the introsort variant, which switches to heapsort when a bad case is detected. If it is known in advance that heapsort is going to be necessary, using it directly will be faster than waiting for introsort to switch to it.</p> </blockquote>
2,413,029
Auto Shutdown and Start Amazon EC2 Instance
<p>Can I automatically start and terminate my Amazon instance using Amazon API? Can you please describe how this can be done? I ideally need to start the instance and stop the instance at specified time intervals every day.</p>
9,879,334
14
4
null
2010-03-09 22:21:38.703 UTC
38
2018-12-11 11:12:03.09 UTC
null
null
null
null
170,883
null
1
93
api|amazon-ec2|amazon-web-services
74,594
<p>Just in case somebody stumbles on this ye old question, nowadays you can achieve the same thing by adding a schedule to an auto scaling group: increase the amount of instances in an auto scaling group to 1 at certain times and decrease it back to 0 afterwards.</p> <p>And since this answer is getting a lot of views, I thought to link to a very helpful guide about this: <a href="http://alestic.com/2011/11/ec2-schedule-instance">Running EC2 Instances on a Recurring Schedule with Auto Scaling</a></p>
62,105,880
React Context Api vs Local Storage
<p>I have some general questions which are bothering me regarding the context API and local storage.</p> <p>When to use local storage?, when to use the Context API and when would I use both?</p> <p>I know that to persist data after the refresh I need something like local storage or session storage, so do I ditch the context API entirely and just store everything in the local storage? this way I can not only store data but also keep it on refresh? some insight would be really helpful.</p> <p>What are some pros and cons?</p>
62,106,152
1
0
null
2020-05-30 17:01:19.857 UTC
9
2022-06-08 18:17:02.81 UTC
2020-05-30 17:22:59.263 UTC
null
7,882,470
null
12,684,838
null
1
12
javascript|reactjs|local-storage|react-context
17,377
<p>Context API vs Local storage is <a href="https://www.wikiwand.com/en/Apples_and_oranges" rel="nofollow noreferrer">apples vs oranges comparison</a>.</p> <p><a href="https://reactjs.org/docs/context.html#contextprovider" rel="nofollow noreferrer">Context API</a> is meant for <strong>sharing state</strong> in the component tree.</p> <blockquote> <p>Context provides a way to <strong>pass data through the component tree</strong> without having to pass props down manually at every level.</p> </blockquote> <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage" rel="nofollow noreferrer">Local Storage</a> is for storing data between sessions.</p> <blockquote> <p>The read-only localStorage property allows you to access a Storage object for the Document's origin; <strong>the stored data is saved across browser sessions</strong>.</p> </blockquote> <p>The right comparison <strong>might be</strong> <a href="https://stackoverflow.com/questions/3220660/local-storage-vs-cookies?rq=1">Local Storage vs Cookies</a>, Context API vs State-Management Library (not really, since <a href="https://blog.isquaredsoftware.com/2021/01/context-redux-differences/" rel="nofollow noreferrer">Context is not a state management tool</a>).</p> <hr /> <p>While you can store everything on the local storage (although it's not scalable and maintainable) it won't be useful.</p> <p>It won't be useful because <strong>you can't notify your components on state change</strong>, you need to use any React's API for it.</p> <p>Usually local storage is used for session <strong>features</strong> like saving user settings, favorite themes, auth tokens, etc.</p> <p>And usually, you read <strong>once</strong> from local storage on application start, and use a custom hook to update its keys on related data change.</p> <p>Here is a helpful recipe for <a href="https://usehooks.com/useLocalStorage/" rel="nofollow noreferrer"><code>useLocalStorage</code></a> custom hook:</p> <pre><code>function useLocalStorage(key, initialValue) { // State to store our value // Pass initial state function to useState so logic is only executed once const [storedValue, setStoredValue] = useState(() =&gt; { try { // Get from local storage by key const item = window.localStorage.getItem(key); // Parse stored json or if none return initialValue return item ? JSON.parse(item) : initialValue; } catch (error) { // If error also return initialValue console.log(error); return initialValue; } }); // Return a wrapped version of useState's setter function that ... // ... persists the new value to localStorage. const setValue = value =&gt; { try { // Allow value to be a function so we have same API as useState const valueToStore = value instanceof Function ? value(storedValue) : value; // Save state setStoredValue(valueToStore); // Save to local storage window.localStorage.setItem(key, JSON.stringify(valueToStore)); } catch (error) { // A more advanced implementation would handle the error case console.log(error); } }; return [storedValue, setValue]; } </code></pre>
10,781,965
Using Moq.It.IsAny to test a string starts with something
<p>Is it possible to use Moq to say a method accepts a string that starts with "ABC" for example.</p> <p>As an example something like this:</p> <pre><code>logger.Verify(x =&gt; x.WriteData(Moq.It.IsAny&lt;string&gt;().StartsWith("ABC")), Times.Exactly(3)); </code></pre> <p>That wont compile but hopefully it illustrates my point</p>
10,781,979
2
0
null
2012-05-28 09:02:22.703 UTC
2
2020-09-21 21:47:48.88 UTC
null
null
null
null
84,539
null
1
40
c#|.net|unit-testing|moq
16,215
<p>try:</p> <pre><code>logger.Verify(x =&gt; x.WriteData(Moq.It.Is&lt;string&gt;(str =&gt; str.StartsWith(&quot;ABC&quot;))), Times.Exactly(3)); </code></pre> <p>you can see another example of It.Is:</p> <pre><code>// matching Func&lt;int&gt;, lazy evaluated mock.Setup(foo =&gt; foo.Add(It.Is&lt;int&gt;(i =&gt; i % 2 == 0))).Returns(true); </code></pre> <p>that comes from Moq documentation: <a href="https://github.com/Moq/moq4/wiki/Quickstart" rel="noreferrer">https://github.com/Moq/moq4/wiki/Quickstart</a></p>
5,867,534
how to save canvas data to file
<p>i am using node.js to save canvas to image img in writeFile is extractedby using toDataURL on my canvas element. it doenot save file here is my code</p> <pre><code>var fs = IMPORTS.require('fs'); var path = IMPORTS.require('path'); path.exists('images/', function(exists){ if (exists) { fs.writeFile('images/icon.png', img, function(err){ if (err) callback({ error: false, reply: err }); console.log('Resized and saved in'); callback({ error: false, reply: 'success.' }); }); } else { callback({ error: true, reply: 'File did not exist.' }); } }); </code></pre>
5,971,674
2
1
null
2011-05-03 09:22:41.4 UTC
19
2021-07-05 04:08:34.843 UTC
null
null
null
null
735,824
null
1
47
javascript|html|node.js
45,395
<p>Here is a literal example of how to save canvas data to a file in Nodejs. The variable <code>img</code> is a string generated by <code>canvas.toDataURL()</code>. I've assumed you already know how to POST that string from the browser to your Nodejs server.</p> <p>HTML snippet that generates the sample image I used:</p> <pre><code>&lt;canvas id=&quot;foo&quot; width=&quot;20px&quot; height=&quot;20px&quot;&gt;&lt;/canvas&gt; &lt;script&gt; var ctx = $('#foo')[0].getContext('2d'); for (var x = 0; x &lt; 20; x += 10) { for (var y = 0; y &lt; 20; y += 10) { if (x == y) { ctx.fillStyle = '#000000'; } else { ctx.fillStyle = '#8888aa'; } ctx.fillRect(x, y, 10, 10); } } console.log($('#foo')[0].toDataURL()); &lt;/script&gt; </code></pre> <p>Nodejs snippet to decode the base64 data and save the image:</p> <pre><code>const fs = require(&quot;fs&quot;).promises; (async () =&gt; { // string generated by canvas.toDataURL() const img = &quot;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0&quot; + &quot;NAAAAKElEQVQ4jWNgYGD4Twzu6FhFFGYYNXDUwGFpIAk2E4dHDRw1cDgaCAASFOffhEIO&quot; + &quot;3gAAAABJRU5ErkJggg==&quot;; // strip off the data: url prefix to get just the base64-encoded bytes const data = img.replace(/^data:image\/\w+;base64,/, &quot;&quot;); const buf = Buffer.from(data, &quot;base64&quot;); await fs.writeFile(&quot;image.png&quot;, buf); })(); </code></pre> <p>Output:</p> <p><img src="https://i.stack.imgur.com/8pkrK.png" alt="enter image description here" /></p>
23,180,765
Redis keyspace notifications with StackExchange.Redis
<p>I've looking around and I'm unable to find how to perform a subscription to keyspace notifications on Redis using StackExchange.Redis library.</p> <p>Checking available tests I've found pubsub using channels, but this is more to work like a service bus/queueing rather than subscribing to specific Redis key events.</p> <p><strong><em>Is it possible to take advantage of this Redis feature using StackExchange.Redis?</em></strong></p>
23,181,085
2
0
null
2014-04-20 09:51:50.523 UTC
12
2022-08-22 07:08:51.227 UTC
null
null
null
null
411,632
null
1
20
c#|.net|redis|publish-subscribe|stackexchange.redis
12,989
<p>The regular subscriber API should work fine - there is no assumption on use-cases, and this should work fine.</p> <p>However, I do kinda agree that this is inbuilt functionality that could perhaps benefit from helper methods on the API, and perhaps a different delegate signature - to encapsulate the syntax of the keyapace notifications so that people don't need to duplicate it. For that: I suggest you log an issue so that it doesn't get forgotten.</p> <h2>Simple sample of how to subscribe to a keyspace event</h2> <p>First of all, it's important to check that Redis keyspace events are enabled. For example, events should be enabled on keys of type <em>Set</em>. This can be done using <code>CONFIG SET</code> command:</p> <pre><code>CONFIG SET notify-keyspace-events KEs </code></pre> <p>Once keyspace events are enabled, it's just about subscribing to the pub-sub channel:</p> <pre><code>using (ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("localhost")) { IDatabase db = connection.GetDatabase(); ISubscriber subscriber = connection.GetSubscriber(); subscriber.Subscribe("__keyspace@0__:*", (channel, value) =&gt; { if ((string)channel == "__keyspace@0__:users" &amp;&amp; (string)value == "sadd") { // Do stuff if some item is added to a hypothethical "users" set in Redis } } ); } </code></pre> <p>Learn more about keyspace events <a href="http://redis.io/topics/notifications">here</a>.</p>
58,861,962
Error converting YAML to JSON: did not find expected key
<p>I just created a new Helm chart but when I run <code>helm install --dry-run --debug</code> I get:</p> <p>Error: YAML parse error on multi-camera-tracking/templates/multi-camera-tracking.yaml: error converting YAML to JSON: yaml: line 30: did not find expected key</p> <p>And this is my Yaml file:</p> <pre><code>--- # apiVersion: apps/v1beta1 apiVersion: apps/v1 kind: StatefulSet metadata: name: multi-camera-tracking annotations: Process: multi-camera-tracking labels: io.kompose.service: multi-camera-tracking spec: serviceName: multi-camera-tracking replicas: 1 selector: matchLabels: io.kompose.service: multi-camera-tracking podManagementPolicy: "Parallel" template: metadata: labels: io.kompose.service: multi-camera-tracking spec: containers: - name: multi-camera-tracking env: - name: MCT_PUB_PORT value: {{ .Values.MCT_PUB_PORT | quote }} - name: SCT_IP_ADDR_CSV value: {{ .Values.SCT_IP_ADDR_CSV | quote }} - name: SCT_PUB_PORT_CSV value: {{ .Values.SCT_PUB_PORT1 | quote }}, {{ .Values.SCT_PUB_PORT2 | quote }} image: {{ .Values.image_multi_camera_tracking }} #name: multi-camera-tracking ports: - containerPort: {{ .Values.MCT_PUB_PORT }} resources: requests: cpu: 0.1 memory: 250Mi limits: cpu: 4 memory: 10Gi readinessProbe: exec: command: - ls - /tmp initialDelaySeconds: 5 periodSeconds: 60 restartPolicy: Always #imagePullSecrets: #- name: wwssecret --- apiVersion: v1 kind: Service metadata: annotations: Process: multi-camera-tracking creationTimestamp: null labels: io.kompose.service: multi-camera-tracking name: multi-camera-tracking spec: ports: - name: "MCT_PUB_PORT" port: {{ .Values.MCT_PUB_PORT }} targetPort: {{ .Values.MCT_PUB_PORT }} selector: io.kompose.service: multi-camera-tracking status: loadBalancer: {} </code></pre> <p>The strange thing is I have created multiple other helm charted and they all are very similar to this but this one doesn't work and produces error.</p>
58,874,298
7
0
null
2019-11-14 16:53:01.293 UTC
3
2022-09-15 07:55:11.77 UTC
null
null
null
null
5,553,963
null
1
11
kubernetes|yaml|kubernetes-helm
53,186
<p>I found the reason why it is not working. First of all, it is allowed to have comma-separated values but the problematic part was the quotations.</p> <p>This is the wrong syntax:</p> <pre><code>value: {{ .Values.SCT_PUB_PORT1 | quote }}, {{ .Values.SCT_PUB_PORT2 | quote }} </code></pre> <p>And this is the correct one:</p> <pre><code>value: {{ .Values.SCT_PUB_PORT1 }}, {{ .Values.SCT_PUB_PORT2 }} </code></pre>
41,211,875
angularjs 1.6.0 (latest now) routes not working
<p>I was expecting to see this question on Stackoverflow but didn't. Apparently I'm the only one having this problem that seems to me to be very common.</p> <p>I have a basic project I am working on but the routes don't seem to work even though everything I've done so far seems to be right.</p> <p>I have this piece of html in my <code>index.html</code> file:</p> <pre><code>&lt;html&gt; &lt;head ng-app="myApp"&gt; &lt;title&gt;New project&lt;/title&gt; &lt;script src="https://code.angularjs.org/1.6.0/angular.min.js"&gt;&lt;/script&gt; &lt;script src="https://code.angularjs.org/1.6.0/angular-route.min.js"&gt;&lt;/script&gt; &lt;script src="app.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="#/add-quote"&gt;Add Quote&lt;/a&gt; &lt;div ng-view &gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>and here is my <code>app.js</code>:</p> <pre><code>var app = angular.module('myApp', ['ngRoute']); app.config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/add-quote', { templateUrl: 'views/add_quote.html', controller: 'QuoteCtrl' }) .otherwise({ redirectTo: '/' }); }]); </code></pre> <p>Now when I just visit the page, here is what I get in the url:</p> <blockquote> <p><a href="http://localhost:8000/admin#!/">http://localhost:8000/admin#!/</a></p> </blockquote> <p>and when I click on the <code>Add quote</code> button, I get this:</p> <blockquote> <p><a href="http://localhost:8000/admin#!/#%2Fadd-quote">http://localhost:8000/admin#!/#%2Fadd-quote</a></p> </blockquote> <p>What can be the problem here? Thanks for help</p>
41,213,016
5
1
null
2016-12-18 19:09:07.233 UTC
34
2019-11-20 10:48:35.18 UTC
2018-07-16 17:19:29.31 UTC
null
5,535,245
null
5,293,064
null
1
101
angularjs|angular-routing|ngroute|angularjs-ng-route|angularjs-1.6
42,815
<p>Simply use hashbang <code>#!</code> in the href:</p> <pre><code> &lt;a href=&quot;#!/add-quote&quot;&gt;Add Quote&lt;/a&gt; </code></pre> <hr /> <p>Due to <a href="https://github.com/angular/angular.js/commit/aa077e81129c740041438688dff2e8d20c3d7b52" rel="noreferrer">aa077e8</a>, the default hash-prefix used for $location hash-bang URLs has changed from the empty string (<code>''</code>) to the bang (<code>'!'</code>).</p> <p>If you actually want to have no hash-prefix, then you can restore the previous behavior by adding a configuration block to your application:</p> <pre><code>appModule.config(['$locationProvider', function($locationProvider) { $locationProvider.hashPrefix(''); }]); </code></pre> <p>For more information, see</p> <ul> <li><a href="https://github.com/angular/angular.js/pull/14202" rel="noreferrer">AngularJS GitHub Pull #14202 Changed default hashPrefix to '!'</a></li> <li><a href="https://docs.angularjs.org/guide/migration#commit-aa077e8" rel="noreferrer">AngularJS Guide - Migration - aa0077e8</a></li> </ul> <hr /> <p><em>Sorry to get on my high horse but... How did this get released? This is massive, breaking bug. — <a href="https://stackoverflow.com/users/436725/milothegreat">@MiloTheGreat</a></em></p> <blockquote> <p><strong>The breaking change as by #14202 should be reverted as the reference specification was already officially deprecated #15715</strong></p> <p><em>I'm going to close this issue because we haven't got any feedback. Feel free to reopen this issue if you can provide new feedback.</em></p> <p>— <a href="https://github.com/angular/angular.js/issues/15715#issuecomment-281785369" rel="noreferrer">https://github.com/angular/angular.js/issues/15715#issuecomment-281785369</a></p> </blockquote>
34,078,208
Passing object by reference to std::thread in C++11
<p>Why can't you pass an object by reference when creating a <code>std::thread</code> ?</p> <p>For example the following snippit gives a compile error:</p> <pre><code>#include &lt;iostream&gt; #include &lt;thread&gt; using namespace std; static void SimpleThread(int&amp; a) // compile error //static void SimpleThread(int a) // OK { cout &lt;&lt; __PRETTY_FUNCTION__ &lt;&lt; ":" &lt;&lt; a &lt;&lt; endl; } int main() { int a = 6; auto thread1 = std::thread(SimpleThread, a); thread1.join(); return 0; } </code></pre> <p>Error:</p> <pre><code>In file included from /usr/include/c++/4.8/thread:39:0, from ./std_thread_refs.cpp:5: /usr/include/c++/4.8/functional: In instantiation of ‘struct std::_Bind_simple&lt;void (*(int))(int&amp;)&gt;’: /usr/include/c++/4.8/thread:137:47: required from ‘std::thread::thread(_Callable&amp;&amp;, _Args&amp;&amp; ...) [with _Callable = void (&amp;)(int&amp;); _Args = {int&amp;}]’ ./std_thread_refs.cpp:19:47: required from here /usr/include/c++/4.8/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of&lt;void (*(int))(int&amp;)&gt;’ typedef typename result_of&lt;_Callable(_Args...)&gt;::type result_type; ^ /usr/include/c++/4.8/functional:1727:9: error: no type named ‘type’ in ‘class std::result_of&lt;void (*(int))(int&amp;)&gt;’ _M_invoke(_Index_tuple&lt;_Indices...&gt;) ^ </code></pre> <p>I've changed to passing a pointer, but is there a better work around?</p>
34,078,246
4
0
null
2015-12-03 23:25:17.547 UTC
25
2021-03-10 10:22:33.993 UTC
2020-01-20 00:55:17.6 UTC
null
12,657,070
null
525,743
null
1
91
c++|multithreading|c++11|pass-by-reference|stdthread
54,771
<p>Explicitly initialize the thread with a <a href="http://en.cppreference.com/w/cpp/utility/functional/ref" rel="noreferrer"><code>reference_wrapper</code> by using <code>std::ref</code></a>:</p> <pre><code>auto thread1 = std::thread(SimpleThread, std::ref(a)); </code></pre> <p>(or <code>std::cref</code> instead of <code>std::ref</code>, as appropriate). Per notes from <a href="http://en.cppreference.com/w/cpp/thread/thread/thread" rel="noreferrer">cppreference on <code>std:thread</code></a>:</p> <blockquote> <p>The arguments to the thread function are moved or copied by value. If a reference argument needs to be passed to the thread function, it has to be wrapped (e.g. with <code>std::ref</code> or <code>std::cref</code>). </p> </blockquote>
18,181,439
Setting different config for different repositories
<p>I was wondering how am I going to change the contents of the command <code>git config --list</code>? I am going to pull/fork a repository from <a href="https://github.com" rel="noreferrer">GitHub</a>. I am going to configure such repositories on both of my Windows, Linux and Mac workstations.</p>
18,181,510
1
3
null
2013-08-12 07:18:07.797 UTC
13
2019-03-10 01:39:34.053 UTC
2019-03-10 01:39:34.053 UTC
null
6,862,601
null
999,452
null
1
43
git|github
36,779
<p>If you want to set up configurations that are specific for a particular repository, you have two options, to configure it from the command line, or edit the repo's config file in an editor.</p> <h3>Option 1: Configure via command line</h3> <p>Simply use the command line, <code>cd</code> into the root of your Git repo, and run <code>git config</code>, <strong><em>without</em></strong> the <code>--system</code> and the <code>--global</code> flags, which are for configuring your machine and user Git settings, respectively:</p> <pre><code>cd &lt;your-repo&gt; git config &lt;setting-name&gt; &lt;setting-value&gt; git config &lt;setting-name&gt;=&lt;setting-value&gt; # alternate syntax </code></pre> <h3>Option 2: Edit config file directly</h3> <p>Your other option is to edit the repo config file directly. With a default Git clone, it's usually the <code>.git/config</code> file in your repo's root folder. Just open that file in an editor and starting adding your settings, or invoke an editor for it at the command line using <code>git config --edit</code>.</p> <h3>Resources</h3> <p>You can learn more about configuring Git at the <a href="https://www.kernel.org/pub/software/scm/git/docs/git-config.html" rel="noreferrer">official Linux Kernel Git documentation for <code>git config</code></a>. In particular, you may be interested in seeing an <a href="https://www.kernel.org/pub/software/scm/git/docs/git-config.html#_example" rel="noreferrer">example Git config</a>:</p> <pre><code># Core variables [core] ; Don't trust file modes filemode = false # Our diff algorithm [diff] external = /usr/local/bin/diff-wrapper renames = true [branch "devel"] remote = origin merge = refs/heads/devel # Proxy settings [core] gitProxy="ssh" for "kernel.org" gitProxy=default-proxy ; for the rest [include] path = /path/to/foo.inc ; include by absolute path path = foo ; expand "foo" relative to the current file path = ~/foo ; expand "foo" in your $HOME directory </code></pre> <h2>Edit</h2> <p>Addressing the <a href="https://stackoverflow.com/questions/18181439/git-different-config-for-different-repository/18181510?noredirect=1#comment26641614_18181510">original poster's question about how to change <code>user.name</code> and <code>user.email</code> per repository</a>, here is how to do it via the command line. Switch to each repository, and run the following:</p> <pre><code>git config user.name "&lt;name&gt;" git config user.email "&lt;email&gt;" </code></pre> <p>Since you're not using the <code>--system</code> or the <code>--global</code> flags, the above commands will apply to whichever repo you have in your terminal working directory only.</p>
32,641,858
What is the best practice for Enterprise level application architecture using MVC5?
<p>I was wondering what is the best practice for enterprise level architecture based on MVC5. I mean selection between multiple layer or multiple project in one solution? and or maybe more than one solution? any good example project?</p>
38,984,444
2
0
null
2015-09-18 00:05:17.67 UTC
13
2017-02-16 09:21:28.517 UTC
null
null
null
null
3,743,442
null
1
20
architecture|asp.net-mvc-5|enterprise|solution
17,635
<p>Since my question has been visited a lot in the last year and there is no solid answer as I am aware of that, I decided to provide a comprehensive answer as much as possible. This answer is based on some actual projects experience and with few expert consultations:</p> <ol> <li>First of all, it is important to note that in software design process, there is nothing like solid right and wrong. As long as an approach works for your project and fits well, it is <code>right</code> and if it doesn’t, it is <code>wrong</code>. There are no rigid principals in software design. There are <code>Project needs and specifications</code>. But generally, it has been accepted using <code>Design Patterns and Principles</code> makes project more <code>robust</code>, <code>reliable</code> and <code>easy to maintain</code> and make your code <code>loosely coupled and highly cohesive</code>.</li> <li>The whole story of <code>Software Design and Architecture</code> is about how you could manage your project easily and how you could maintain your future changes. Think about which approach gives you best answer on them. That will be the best for you. Don't think too much about <code>Professionalism</code>! .Your project grows by time and gets more mature. So just think about your project!</li> <li>As a first step and for Enterprise level application architecture, always try to follow <code>Separation of Concerns</code> or <code>SoC</code>. It means you should have different tiers for different layers of your project. It is highly recommended to use different <strong>project</strong> in your <strong>solution</strong> for <code>Data Access Layer</code>, <code>Domain Entities</code>, <code>Business Layer</code>and <code>Presentation Layer</code>. In MVC5 project, it is better to use <code>Class Library Project</code> for <code>Data Access Layer</code>, <code>Domain Entities</code>, <code>Business Layer</code> and a MVC project for <code>Presentation Layer</code>.</li> <li><code>Data Access Layer</code> is the project that faces to database and database interactions. You could have all your <code>Entity Framework</code> or similar entities in this project. Having separated layer for database layer means in the case of changing your project data warehouse, the only thing you need to change is changing this project and some minor changes on your <code>Business Layer</code>. All other projects in your solution remain intact. So you could easily move from MS Sql to Oracle or from <code>Entity Framework</code> to <code>NHibernate</code>.</li> <li><code>Domain Entities</code> is the project I use to define all my solution level interfaces, classes, enums and variables. This project keeps integrity throughout my solution on my classes and my methods. My all classes in whole solution are inherited from interfaces in this project. So I have <strong>one place</strong> to change my classes or global variables and it means <code>Easy to Maintain</code> for future in my solution and easy to understand for newly joined developers to the project.</li> <li><code>Business Layer</code> is the place I put my all business logic including <code>Business Entities</code> and <code>Business Services</code>. The whole idea about this layer is having one place to keep your all business methods and interactions. All calculations, object modification and all logic about data including saving, retrieving, changing and so on should happen in this section. By having this layer in your project, you could have different consumers at the same time, for example one native <code>MVC</code> and one <code>Web API</code> layer. Or you could provide different feeding based on different business services consumers specifications. It is highly recommended to avoid putting any business logic into controller section of MVC layer. Having any business logic inside controllers means you using your presentation layer as business logic layer and it violates <code>Separation of Concerns</code>. Then it won’t be easy to change from one presentationlayer to other or having different type of consumers for your solution. It is better to keep controller section in MVC as slim as possible. The controllers should only have logic and methods directly related to <code>View Models</code>. For more information about <code>View Models</code> refer to section <code>7</code>. One thing to remember, It is better to have different <code>Business Services</code> classes based on your solution objects or <code>Business Entities</code>.</li> <li><code>Presentation Layer</code> in MVC solution will be an MVC project. But solution could have other type or more than one Presentation Layers for different consumers or technology. For example you could have one MVC layer and one <code>Web API</code> in one solution. Generally Use Presentation Layer to keep all presentation logic in it. Presentation logic shouldn’t have anything related to business logic or data logic. So question is what is <code>Presentation logic</code>? <code>Presentation logic</code> is logic related to view models. View models are objects customized for views or pages. In most cases, business objects are not suitable to use in views. On the other hand, presentation views usually need some validation logic or presentation logic, for example display name different than original object names. In these cases it is better keep presentation logic separated than business logic to make it easy to change presentation logic or business logic independently and even easy to switch presentation layer for different UI design or changing business logic for having more functionality without fear of any interruption with presentation logic. In the case of using MVC project as presentation layer for solution, all view models should be places in <code>Models</code> section of MVC project and all presentation logic should be placed in <code>Controllers</code> section of project.</li> <li>The last thing to say is for every multi-tier solution, you need frameworks for object to object mapping, for example to convert your business entity to view model. There are some tools for this purposes like <code>AutoMapper</code>, <code>BLToolkit</code>, and <code>EmitMapper</code>.</li> </ol> <hr> <p>Last word: please comment and score <code>question</code> and my <code>answer</code> to make it better!</p>
20,926,909
Python check if function exists without running it
<p>In python how do you check if a function exists without actually running the function (i.e. using try)? I would be testing if it exists in a module.</p>
20,926,976
7
1
null
2014-01-04 21:21:28.883 UTC
4
2022-09-03 21:02:26.107 UTC
2020-01-07 12:01:42.933 UTC
null
2,823,526
null
1,054,287
null
1
46
python|function|python-2.7|try-catch
45,040
<p>You can use <a href="http://docs.python.org/2.7/library/functions.html#dir"><code>dir</code></a> to check if a name is in a module:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; "walk" in dir(os) True &gt;&gt;&gt; </code></pre> <p>In the sample code above, we test for the <a href="http://docs.python.org/2/library/os.html#os.walk"><code>os.walk</code></a> function.</p>
30,234,594
What's the difference between ZonedDateTime and OffsetDateTime?
<p>I've read the documentation, but I still can't get when I should use one or the other: </p> <ul> <li><a href="https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html"><code>OffsetDateTime</code></a></li> <li><a href="https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html"><code>ZonedDateTime</code></a></li> </ul> <p>According to documentation <code>OffsetDateTime</code> should be used when writing date to database, but I don't get why.</p>
30,234,992
2
1
null
2015-05-14 10:08:40.807 UTC
56
2021-05-25 07:47:00.573 UTC
2020-05-15 15:09:33.423 UTC
null
452,775
null
1,328,513
null
1
190
java|java-8|java-time
61,808
<blockquote> <p>Q: What's the difference between java 8 ZonedDateTime and OffsetDateTime?</p> </blockquote> <p>The javadocs say this:</p> <blockquote> <p><em>"<code>OffsetDateTime</code>, <code>ZonedDateTime</code> and <code>Instant</code> all store an instant on the time-line to nanosecond precision. <code>Instant</code> is the simplest, simply representing the instant. <code>OffsetDateTime</code> adds to the instant the offset from UTC/Greenwich, which allows the local date-time to be obtained. <code>ZonedDateTime</code> adds full time-zone rules."</em></p> </blockquote> <p>Source: <a href="https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html" rel="noreferrer">https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html</a></p> <p>Thus the difference between <code>OffsetDateTime</code> and <code>ZonedDateTime</code> is that the latter includes the rules that cover daylight saving time adjustments and various other anomalies. </p> <p>Stated simply:</p> <blockquote> <p><a href="https://en.wikipedia.org/wiki/Time_zone" rel="noreferrer">Time Zone</a> = ( <a href="https://en.wikipedia.org/wiki/UTC_offset" rel="noreferrer">Offset-From-UTC</a> + Rules-For-Anomalies ) </p> </blockquote> <hr> <blockquote> <p>Q: According to documentation <code>OffsetDateTime</code> should be used when writing date to database, but I don't get why.</p> </blockquote> <p>Dates with local time offsets always represent the same instants in time, and therefore have a stable ordering. By contrast, the meaning of dates with full timezone information is unstable in the face of adjustments to the rules for the respective timezones. (And these do happen; e.g. for date-time values in the future.) So if you store and then retrieve a <code>ZonedDateTime</code> the implementation has a problem:</p> <ul> <li><p>It can store the computed offset ... and the retrieved object may then have an offset that is inconsistent with the current rules for the zone-id.</p></li> <li><p>It can discard the computed offset ... and the retrieved object then represents a different point in the absolute / universal timeline than the one that was stored.</p></li> </ul> <p>If you use Java object serialization, the Java 9 implementation takes the first approach. This is arguably the "more correct" way to handle this, but this doesn't appear to be documented. (JDBC drivers and ORM bindings are presumably making similar decisions, and are hopefully getting it right.)</p> <p>But if you are writing an application that manually stores date/time values, or that rely on <code>java.sql.DateTime</code>, then dealing with the complications of a zone-id is ... probably something to be avoided. Hence the advice.</p> <p>Note that dates whose meaning / ordering is unstable over time <em>may be</em> problematic for an application. And since changes to zone rules are an edge case, the problems are liable to emerge at unexpected times.</p> <hr> <p>A (possible) second reason for the advice is that the construction of a <code>ZonedDateTime</code> is ambiguous at the certain points. For example in the period in time when you are "putting the clocks back", combining a local time and a zone-id can give you two different offsets. The <code>ZonedDateTime</code> will consistently pick one over the other ... but this isn't always the correct choice.</p> <p>Now, this could be a problem for any applications that construct <code>ZonedDateTime</code> values that way. But from the perspective of someone building an enterprise application is a bigger problem when the (possibly incorrect) <code>ZonedDateTime</code> values are persistent and used later.</p>
25,870,904
Create a user defined table type in c# to use in sql server stored procedure
<p>I'm trying to write a C# program which creates a whole table to send back to a SQL Server stored procedure.</p> <p>I came across the msdn guide but became incredibly confused: <a href="http://msdn.microsoft.com/en-us/library/cc879253.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/cc879253.aspx</a></p> <p>I tried to use the msdn guide but get an error despite adding references to microsoft.sqlserver.smo, microsoft.sqlserver.connectioninfo, microsoft.sqlserver.management.sdk.sfc as suggested by the compiler. The error is:</p> <blockquote> <p>Set parent failed for userdefinedtabletype.</p> </blockquote> <p>Code snippet based on msdn guide:</p> <pre><code>Server srv = new Server(); Database db = srv.Databases["MyDatabase"]; //fails at this line UserDefinedTableType udtt = new UserDefinedTableType(db, "TestTable"); udtt.Columns.Add(new Column(udtt, "Col1", DataType.Int)); udtt.Create(); </code></pre> <p>I would simply like to be able to build a user defined data table, the only related questions I've found here deal only with creating a user defined table in SQL, not C#.</p> <p>My SQL Server connection code is this:</p> <pre><code> DataSet ds = new DataSet("SQLDatabase"); using (SqlConnection conn = new SqlConnection(Settings.Default.SQLConnectionString)) { SqlCommand sqlComm = new SqlCommand("StoredProcedure", conn); sqlComm.Parameters.AddWithValue("@param", paramValue); sqlComm.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = sqlComm; da.Fill(ds); } </code></pre> <p>Please could someone show me in simple language, how to create a user defined table type in my C# program?</p>
25,871,046
2
0
null
2014-09-16 14:02:32.737 UTC
4
2020-11-15 18:42:54.32 UTC
2020-03-17 19:33:46.457 UTC
null
1,127,428
null
3,929,806
null
1
12
c#|sql-server-2012
38,844
<p>Simplest option is to create a <code>DataTable</code> in C# code and pass it as a parameter to your procedure. Assuming that you have created a User Defined Table Type as:</p> <pre><code>CREATE TYPE [dbo].[userdefinedtabletype] AS TABLE( [ID] [varchar](255) NULL, [Name] [varchar](255) NULL ) </code></pre> <p>then in your C# code you would do:</p> <pre><code>DataTable dt = new DataTable(); dt.Columns.Add("ID", typeof (string)); dt.Columns.Add("Name", typeof (string)); //populate your Datatable SqlParameter param = new SqlParameter("@userdefinedtabletypeparameter", SqlDbType.Structured) { TypeName = "dbo.userdefinedtabletype", Value = dt }; sqlComm.Parameters.Add(param); </code></pre> <p>Remember to specify <code>SqlDbType.Structured</code> as the type of parameter and specify the name you have used in creating your UDT. </p>
8,617,712
difference between "ifndef" and "if !defined" in C?
<p>I have seen <code>#ifndef ABC</code> and <code>#if !defined (ABC)</code> in the same C source file.</p> <p>Is there subtle difference between them? (If it is a matter of style, why would someone use them in the same file)</p>
8,617,732
2
0
null
2011-12-23 15:27:48.633 UTC
6
2011-12-23 15:32:57.37 UTC
null
null
null
null
1,064,959
null
1
48
c|include-guards
25,577
<p>No, there's no difference between the two when used that way. The latter form (using <code>defined()</code>) is useful when the initial <code>#if</code> or one of the subsequent <code>#elif</code> conditions needs a more complex test. <code>#ifdef</code> will still work, but it might be clearer using <code>#if defined()</code> in that case. For example, if it needs to test if more than one macro is defined, or if it equals a specific value.</p> <p>The variance (using both in a file) could depend on specific subtleties in usage, as mentioned above, or just poor practice, by being inconsistent.</p>
8,674,387
Vim, how to reload syntax highlighting
<p>When I execute Rmodel, Rcontroller and others in Vim. I see only white text. But when I go to next buffer and then go back by <code>:bn</code> and <code>:bl</code>, colors are working.</p> <p>This is my .vim folder <a href="https://github.com/regedarek/dotvim" rel="noreferrer">https://github.com/regedarek/dotvim</a></p>
17,189,261
7
0
null
2011-12-29 22:48:35.803 UTC
27
2020-01-12 13:51:46.45 UTC
2017-07-24 14:18:49.483 UTC
null
1,389,898
null
1,103,892
null
1
94
vim|syntax-highlighting|rails.vim
27,042
<p>Use <code>:syntax sync fromstart</code></p> <p>I got that tip from <a href="http://vim.wikia.com/wiki/Fix_syntax_highlighting" rel="noreferrer">http://vim.wikia.com/wiki/Fix_syntax_highlighting</a></p> <p>That article also suggests creating a mapping for that command e.g. to map F12:</p> <pre><code>noremap &lt;F12&gt; &lt;Esc&gt;:syntax sync fromstart&lt;CR&gt; inoremap &lt;F12&gt; &lt;C-o&gt;:syntax sync fromstart&lt;CR&gt; </code></pre>
8,960,777
Pass parameter to fabric task
<p>How can I pass a parameter to a fabric task when calling "fab" from the command line? For example:</p> <pre class="lang-python prettyprint-override"><code>def task(something=''): print "You said %s" % something </code></pre> <pre class="lang-none prettyprint-override"><code>$ fab task "hello" You said hello Done. </code></pre> <p>Is it possible to do this without prompting with <code>fabric.operations.prompt</code>?</p>
8,960,883
5
0
null
2012-01-22 11:40:15.053 UTC
28
2021-04-01 12:57:50.393 UTC
2014-09-06 01:00:51.683 UTC
null
70,157
null
223,090
null
1
129
python|fabric
52,091
<p>Fabric 2 task arguments documentation:</p> <p><a href="http://docs.pyinvoke.org/en/latest/concepts/invoking-tasks.html#task-command-line-arguments" rel="noreferrer">http://docs.pyinvoke.org/en/latest/concepts/invoking-tasks.html#task-command-line-arguments</a></p> <hr> <p>Fabric 1.X uses the following syntax for passing arguments to tasks:</p> <pre><code> fab task:'hello world' fab task:something='hello' fab task:foo=99,bar=True fab task:foo,bar </code></pre> <p>You can read more about it in <a href="http://docs.fabfile.org/en/latest/usage/fab.html#per-task-arguments" rel="noreferrer">Fabric docs</a>.</p>
8,541,081
CSS: Set a background color which is 50% of the width of the window
<p>Trying to achieve a background on a page that is "split in two"; two colors on opposite sides (seemingly done by setting a default <code>background-color</code> on the <code>body</code> tag, then applying another onto a <code>div</code> that stretches the entire width of the window).</p> <p>I did come up with a solution but unfortunately the <code>background-size</code> property doesn't work in IE7/8 which is a must for this project -</p> <pre><code>body { background: #fff; } #wrapper { background: url(1px.png) repeat-y; background-size: 50% auto; width: 100%; } </code></pre> <p>Since it's just about solid colors maybe there is a way using only the regular <code>background-color</code> property?</p>
8,541,575
14
0
null
2011-12-16 22:51:14.083 UTC
58
2020-11-11 20:46:34.177 UTC
2011-12-16 23:54:47.277 UTC
null
815,792
null
369,185
null
1
223
css|background-color
686,619
<h1>Older Browser Support</h1> <p>If older browser support is a must, so you can't go with multiple backgrounds or gradients, you're probably going to want to do something like this on a spare <code>div</code> element:</p> <pre class="lang-css prettyprint-override"><code>#background { position: fixed; top: 0; left: 0; width: 50%; height: 100%; background-color: pink; } </code></pre> <p>Example: <a href="http://jsfiddle.net/PLfLW/1704/" rel="noreferrer">http://jsfiddle.net/PLfLW/1704/</a></p> <p>The solution uses an extra fixed div that fills half the screen. Since it's fixed, it will remain in position even when your users scroll. You may have to fiddle with some z-indexes later, to make sure your other elements are above the background div, but it shouldn't be too complex.</p> <p>If you have issues, just make sure the rest of your content has a z-index higher than the background element and you should be good to go.</p> <hr> <h1>Modern Browsers</h1> <p>If newer browsers are your only concern, there are a couple other methods you can use:</p> <p><strong>Linear Gradient:</strong></p> <p>This is definitely the easiest solution. You can use a linear-gradient in the background property of the body for a variety of effects.</p> <pre class="lang-css prettyprint-override"><code>body { height: 100%; background: linear-gradient(90deg, #FFC0CB 50%, #00FFFF 50%); } </code></pre> <p>This causes a hard cutoff at 50% for each color, so there isn't a "gradient" as the name implies. Try experimenting with the "50%" piece of the style to see the different effects you can achieve.</p> <p>Example: <a href="http://jsfiddle.net/v14m59pq/2/" rel="noreferrer">http://jsfiddle.net/v14m59pq/2/</a></p> <p><strong>Multiple Backgrounds with background-size:</strong></p> <p>You can apply a background color to the <code>html</code> element, and then apply a background-image to the <code>body</code> element and use the <code>background-size</code> property to set it to 50% of the page width. This results in a similar effect, though would really only be used over gradients if you happen to be using an image or two.</p> <pre class="lang-css prettyprint-override"><code>html { height: 100%; background-color: cyan; } body { height: 100%; background-image: url('http://i.imgur.com/9HMnxKs.png'); background-repeat: repeat-y; background-size: 50% auto; } </code></pre> <p>Example: <a href="http://jsfiddle.net/6vhshyxg/2/" rel="noreferrer">http://jsfiddle.net/6vhshyxg/2/</a></p> <hr> <p><strong>EXTRA NOTE:</strong> Notice that both the <code>html</code> and <code>body</code> elements are set to <code>height: 100%</code> in the latter examples. This is to make sure that even if your content is smaller than the page, the background will be at least the height of the user's viewport. Without the explicit height, the background effect will only go down as far as your page content. It's also just a good practice in general.</p>
43,555,282
react.js application showing 404 not found in nginx server
<p>I uploaded react.js application to a server. I'm using nginx server. Application is working fine. But when I go to another page &amp; refresh, the site is not working. It's showing a 404 Not found error.</p> <p>How can I solve this?</p>
43,557,288
9
0
null
2017-04-22 04:37:10.397 UTC
28
2022-08-22 08:10:29.877 UTC
2022-08-04 13:13:55.683 UTC
null
15,993,687
null
7,245,976
null
1
68
reactjs|nginx
66,447
<p>When your <code>react.js</code> app loads, the routes are handled on the frontend by the <code>react-router</code>. Say for example you are at <code>http://a.com</code>. Then on the page you navigate to <code>http://a.com/b</code>. This route change is handled in the browser itself. Now when you refresh or open the url <code>http://a.com/b</code> in the a new tab, the request goes to your <code>nginx</code> where the particular route does not exist and hence you get 404.</p> <p>To avoid this, you need to load the root file(usually index.html) for all non matching routes so that <code>nginx</code> sends the file and the route is then handled by your react app on the browser. To do this you have to make the below change in your <code>nginx.conf</code> or <code>sites-enabled</code> appropiately</p> <pre><code>location / { try_files $uri /index.html; } </code></pre> <p>This tells <code>nginx</code> to look for the specified <code>$uri</code>, if it cannot find one then it send <code>index.html</code> back to the browser. (See <a href="https://serverfault.com/questions/329592/how-does-try-files-work">https://serverfault.com/questions/329592/how-does-try-files-work</a> for more details)</p>
39,916
Programmatically building htpasswd
<p>Is there a programmatic way to build <em>htpasswd</em> files, without depending on OS specific functions (i.e. <code>exec()</code>, <code>passthru()</code>)?</p>
39,963
3
0
null
2008-09-02 16:15:23.197 UTC
11
2017-12-08 13:41:55.063 UTC
2017-12-08 13:41:55.063 UTC
null
1,033,581
Unkwntech
115
null
1
22
php|automation|.htpasswd
20,872
<p>.httpasswd files are just text files with a specific format depending on the hash function specified. If you are using MD5 they look like this:</p> <pre><code>foo:$apr1$y1cXxW5l$3vapv2yyCXaYz8zGoXj241 </code></pre> <p>That's the login, a colon, ,$apr1$, the salt and 1000 times md5 encoded as base64. If you select SHA1 they look like this:</p> <pre><code>foo:{SHA}BW6v589SIg3i3zaEW47RcMZ+I+M= </code></pre> <p>That's the login, a colon, the string {SHA} and the SHA1 hash encoded with base64.</p> <p>If your language has an implementation of either MD5 or SHA1 and base64 you can just create the file like this:</p> <pre><code>&lt;?php $login = 'foo'; $pass = 'pass'; $hash = base64_encode(sha1($pass, true)); $contents = $login . ':{SHA}' . $hash; file_put_contents('.htpasswd', $contents); ?&gt; </code></pre> <p>Here's more information on the format:</p> <p><a href="http://httpd.apache.org/docs/2.2/misc/password_encryptions.html" rel="noreferrer">http://httpd.apache.org/docs/2.2/misc/password_encryptions.html</a></p>
859,383
How to open a new window below a split created by vimdiff?
<p>If, at a command prompt, I run</p> <pre><code>vimdiff file1 file2 </code></pre> <p>I get a vim instance that has two files open side-by-side, something like this:</p> <pre><code>╔═══════╤═══════╗ ║ │ ║ ║ │ ║ ║ file1 │ file2 ║ ║ │ ║ ║ │ ║ ╚═══════╧═══════╝ </code></pre> <p>This is very nice, but sometimes I want to open a third file to look at. I don't want to create another vertical split, because otherwise the lines will be so short I'd be scrolling horizontally all the time just to read them. But occupying a few lines at the bottom of the screen wouldn't hurt. So, how can I go from the above to the following:</p> <pre><code>╔═══════╤═══════╗ ║ │ ║ ║ file1 │ file2 ║ ║ │ ║ ╟───────┴───────╢ ║ file3 ║ ╚═══════════════╝ </code></pre> <p>I've tried using <code>:sp file3</code>, but I just end up with this (supposing I ran the command while the cursor was in file1):</p> <pre><code>╔═══════╤═══════╗ ║ file3 │ ║ ║ │ ║ ╟───────┤ file2 ║ ║ file1 │ ║ ║ │ ║ ╚═══════╧═══════╝ </code></pre> <p>Thanks in advance for your help!</p>
859,455
3
5
null
2009-05-13 17:47:23.693 UTC
9
2010-01-19 23:51:22.27 UTC
2009-05-15 11:44:15.19 UTC
null
71,394
user82216
null
null
1
26
vim|split|text-editor|vimdiff
2,415
<p>Use</p> <pre><code>:botright split </code></pre> <p>and open a new file inside.</p>
506,521
Set TextBlock to be entirely bold when DataBound in WPF
<p>I have a databound TextBlock control (which is being used inside a DataTemplate to display items in a ListBox) and I want to make all the text in the control bold. I can't seem to find a property in the properties explorer to set the whole text to bold, and all I can find online is the use of the <code>&lt;Bold&gt;</code> tag inside the TextBlock, but I can't put that in as the data is coming directly from the data source.</p> <p>There must be a way to do this - but how? I'm very inexperienced in WPF so I don't really know where to look.</p>
506,626
3
0
null
2009-02-03 09:45:01.21 UTC
1
2009-02-03 10:24:27.23 UTC
null
null
null
robintw
1,912
null
1
28
c#|.net|wpf|xaml|textblock
48,532
<p>Am I missing something, or do you just need to set the FontWeight property to "Bold"?</p> <pre><code>&lt;TextBlock FontWeight="Bold" Text="{Binding Foo}" /&gt; </code></pre>
1,188,893
Is there a way in Ruby/Rails to execute code that is in a string?
<p>So I have a database of different code samples (read snippets). The code samples are created by users. Is there a way in Rails to execute it?</p> <p>So for example I have the following code in my database (with id=123):</p> <pre><code>return @var.reverse </code></pre> <p>Is there a way for me to execute it? Something like:</p> <pre><code>@var = 'Hello' @result = exec(CodeSample.find(123)) </code></pre> <p>So the result would be 'olleH'</p>
1,188,921
3
0
null
2009-07-27 15:36:28.71 UTC
12
2016-04-18 10:56:40.417 UTC
2014-05-03 00:05:18.17 UTC
null
1,107,398
null
106,410
null
1
57
ruby-on-rails|ruby|scripting
44,629
<p>You can use <a href="http://ruby-doc.org/core/classes/Kernel.html#M005922" rel="noreferrer"><code>eval</code></a>:</p> <pre><code>code = '@var.reverse' @var = 'Hello' @result = eval(code) # =&gt; "olleH" </code></pre> <p>But be very careful in doing so; you're giving that code full access to your system. Try out <code>eval('exit()')</code> and see what happens.</p>
22,293,118
Can we reclone a git repository from the existing local repository
<p>Since git is a distributed VCS, it should have complete history of changes done to a repository.</p> <p>So can we <strong>extract</strong> that version of repo which was cloned first?</p> <p>Actually I have done a lot of changes in my existing local repo. and do not want to revert back to the original state by losing the data. But I want to extract the original repository(which I cloned initially) to some other location using existing git objects(blob/tree).</p> <p>Note : I don't have the access to git server now.</p>
22,293,652
5
0
null
2014-03-10 06:05:31.433 UTC
null
2019-07-31 19:05:59.487 UTC
2014-03-10 06:25:52.07 UTC
null
1,201,406
null
1,201,406
null
1
7
git|git-clone|git-revert
49,523
<p>Try this:</p> <pre><code>git clone SOURCE_PATH NEW_PATH # clones everything you have committed up to now cd NEW_PATH # go to new clone, don't modify the pre-existing one git reset --hard REV # REV is the revision to "rewind" to (from git log) </code></pre> <p>So you need to figure out explicitly which revision to go back to (Git probably doesn't know which revision you originally cloned, but probably you can figure it out). The first step is just to clone from your local disk to your local disk in a different directory so you can keep your existing work untouched.</p>
67,410,992
Upgrading Android kotlin version to 1.5.0 throwing error message on build
<p>Running with kotlin version '1.4.32' my Android project runs and builds. Trying to upgrade to kotlin '1.5.0' and my build throws:</p> <pre><code>Execution failed for task ':app:kaptDefaultsDebugKotlin'. &gt; A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction &gt; java.lang.reflect.InvocationTargetException (no error message) </code></pre> <p>I am not even sure where to start looking. Anyone else have problems upgrading to kotlin 1.5.0?</p>
67,413,594
15
1
null
2021-05-06 02:17:39.873 UTC
8
2022-08-18 09:45:09.98 UTC
null
null
null
null
1,281,501
null
1
75
android|kotlin
39,036
<p>This is due to Dagger's use of older version of <code>kotlinx-metadata-jvm</code>. See <a href="https://youtrack.jetbrains.com/issue/KT-45885" rel="noreferrer">https://youtrack.jetbrains.com/issue/KT-45885</a></p> <p>Update your dagger to <code>2.34</code></p>
20,251,119
Increase the size of variable-size points in ggplot2 scatter plot
<p>I am plotting a scatter plot where each point has a different size corresponding to the number of observations. Below is the example of code and the image output:</p> <pre><code>rm(list = ls()) require(ggplot2) mydf &lt;- data.frame(x = c(1, 2, 3), y = c(1, 2, 3), count = c(10, 20, 30)) ggplot(mydf, aes(x = x, y = y)) + geom_point(aes(size = count)) ggsave(file = '2013-11-25.png', height = 5, width = 5) </code></pre> <p><img src="https://i.stack.imgur.com/V8pWe.png" alt="enter image description here"></p> <p>This is quite nice, but is there a way to increase the sizes of all of the points? In particular, as it currently is, the point for "10" is too small and thus very hard to see.</p>
20,251,290
1
0
null
2013-11-27 19:14:18.027 UTC
8
2013-11-27 19:23:18.707 UTC
null
null
null
null
856,624
null
1
23
r|ggplot2
51,086
<p>Use:</p> <p><code>&lt;your ggplot code&gt; + scale_size_continuous(range = c(minSize, maxSize))</code></p> <p>where <code>minSize</code> is your minimum point size and <code>maxSize</code> is your maximum point size.</p> <p>Example:</p> <pre><code>ggplot(mydf, aes(x = x, y = y)) + geom_point(aes(size = count)) + scale_size_continuous(range = c(3, 7)) </code></pre>
6,028,231
http status code for an expired link?
<p>guys which is the correct status code for a link that expires in a certain amount of time?</p> <p>I have thought to send a 404 after the expiration but maybe there is a better http status to send.</p> <p>Example of link:</p> <p><code>mysite/dir/062011/file.exe</code> (&lt;- working only within 06-2011)</p> <p>Thanks</p>
6,028,296
3
0
null
2011-05-17 08:33:53.32 UTC
5
2018-11-29 14:26:42.833 UTC
null
null
null
null
496,223
null
1
51
http
33,464
<p>How about 410 "Gone"?<br> See: <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html</a></p>
6,139,952
What is the booting process for ARM?
<p>As we know, for X86 architecture: After we press the power button, machine starts to execute code at 0xFFFFFFF0, then it starts to execute code in BIOS in order to do hardware initialization. After BIOS execution, it use bootloader to load the OS image into memory. At the end, OS code starts to run. For ARM architecture, what is the booting process after use press the power button? Thanks!</p>
6,140,567
3
2
null
2011-05-26 14:09:53.213 UTC
45
2019-01-03 05:01:41.997 UTC
null
null
null
null
620,210
null
1
67
arm|boot|bootloader
72,785
<p>Currently, there are two exception models in the ARM architecture (reset is considered a kind of exception):</p> <p>The classic model, used in pre-Cortex chip and current Cortex-A/R chips. In it, the memory at 0 contains several exception handlers:</p> <pre><code> Offset Handler =============== 00 Reset 04 Undefined Instruction 08 Supervisor Call (SVC) 0C Prefetch Abort 10 Data Abort 14 (Reserved) 18 Interrupt (IRQ) 1C Fast Interrupt (FIQ) </code></pre> <p>When the exception happens, the processor just starts execution from a specific offset, so usually this table contains single-instruction branches to the complete handlers further in the code. A typical classic vector table looks like following:</p> <pre><code>00000000 LDR PC, =Reset 00000004 LDR PC, =Undef 00000008 LDR PC, =SVC 0000000C LDR PC, =PrefAbort 00000010 LDR PC, =DataAbort 00000014 NOP 00000018 LDR PC, =IRQ 0000001C LDR PC, =FIQ </code></pre> <p>At runtime, the vector table can be relocated to 0xFFFF0000, which is often implemented as a tightly-coupled memory range for the fastest exception handling. However, the power-on reset usually begins at 0x00000000 (but in some chips can be set to 0xFFFF0000 by a processor pin).</p> <p>The new microcontroller model is used in the Cortex-M line of chips. There, the vector table at 0 is actually a table of vectors (pointers), not instructions. The first entry contains the start-up value for the SP register, the second is the reset vector. This allows writing the reset handler directly in C, since the processor sets up the stack. Again, the table can be relocated at runtime. The typical vector table for Cortex-M begins like this:</p> <pre><code>__Vectors DCD __initial_sp ; Top of Stack DCD Reset_Handler ; Reset Handler DCD NMI_Handler ; NMI Handler DCD HardFault_Handler ; Hard Fault Handler DCD MemManage_Handler ; MPU Fault Handler DCD BusFault_Handler ; Bus Fault Handler DCD UsageFault_Handler ; Usage Fault Handler [...more vectors...] </code></pre> <p>Note that in the modern complex chips such as OMAP3 or Apple's A4 the first piece of code which is executed is usually not user code but the on-chip Boot ROM. It might check various conditions to determine where to load the user code from and whether to load it at all (e.g. it could require a valid digital signature). In such cases, the user code might have to conform to different start-up conventions.</p>
6,307,127
Hiding Errors When Using Get-ADGroup
<p>I'm working on a script that will build a new group if it doesn't exist. I'm using Get-ADGroup to make sure the group doesn't exist using the following command:</p> <pre><code>$group = get-adgroup $groupName -ErrorAction:SilentlyContinue -WarningAction:SilentlyContinue </code></pre> <p>But when I do I get the following error (I removed any domain specific data from the error):</p> <pre><code>Get-ADGroup : Cannot find an object with identity: '*group name*' under: '*domain*'. At U:\Scripts\Windows\Create-FolderAccessGroup.ps1:23 char:24 + $group = get-adgroup &lt;&lt;&lt;&lt; $groupName -ErrorAction:SilentlyContinue -WarningAction:SilentlyContinue + CategoryInfo : ObjectNotFound: (y:ADGroup) [Get-ADGroup], ADIdentityNot FoundException + FullyQualifiedErrorId : Cannot find an object with identity: '' under: ''.,Microsoft.ActiveDirectory.Management.Commands.GetADGroup </code></pre> <p>I assumed setting ErrorAction and WarningAction to SilentlyContinue would keep this error from being displayed but it hasn't.</p>
6,309,186
4
5
null
2011-06-10 13:38:02.983 UTC
3
2016-09-05 06:48:40.957 UTC
null
null
null
null
4,437
null
1
14
powershell|active-directory
42,326
<pre><code> try {get-adgroup &lt;groupname&gt;} catch { &lt;make new group&gt; } </code></pre>
5,995,812
Python - Decimal to Hex, Reverse byte order, Hex to Decimal
<p>I've been reading up a lot on stuct.pack and hex and the like.</p> <p>I am trying to convert a decimal to hexidecimal with 2-bytes. Reverse the hex bit order, then convert it back into decimal.</p> <p>I'm trying to follow these steps...in python</p> <pre><code>Convert the decimal value **36895** to the equivalent 2-byte hexadecimal value: **0x901F** Reverse the order of the 2 hexadecimal bytes: **0x1F90** Convert the resulting 2-byte hexadecimal value to its decimal equivalent: **8080** </code></pre>
5,995,904
5
3
null
2011-05-13 17:50:11.243 UTC
5
2021-03-12 06:34:31.553 UTC
2018-03-13 04:06:54.34 UTC
null
1,033,581
null
597,153
null
1
3
python|decimal|hex|bit
40,842
<p>Bit shifting to swap upper/lower eight bits:</p> <pre><code>&gt;&gt;&gt; x = 36895 &gt;&gt;&gt; ((x &lt;&lt; 8) | (x &gt;&gt; 8)) &amp; 0xFFFF 8080 </code></pre> <p>Packing and unpacking unsigned short(H) with opposite endianness(&lt;&gt;):</p> <pre><code>&gt;&gt;&gt; struct.unpack('&lt;H',struct.pack('&gt;H',x))[0] 8080 </code></pre> <p>Convert 2-byte little-endian to big-endian...</p> <pre><code>&gt;&gt;&gt; int.from_bytes(x.to_bytes(2,'little'),'big') 8080 </code></pre>
1,476,892
Poster with the 8 phases of translation in the C language
<p>Does anyone have a reference to a poster/one-page pdf or something similar with a list of the eight phases of translation for the C language (the first one being trigraph translation)? I want to have one printed hanging on my wall next to my pc.</p> <p>Update: Sorry for forgetting to specify. I am interested in C90 (although C99 probably is pretty close, <code>_Pragma</code> as mentioned in pmg's answer is C99 specific and I would like to avoid that).</p>
1,479,972
2
0
null
2009-09-25 11:58:39.757 UTC
19
2009-09-25 23:40:25.853 UTC
2009-09-25 14:08:33.553 UTC
null
23,118
null
23,118
null
1
20
c
7,345
<p>ASCII art for the win:</p> <pre><code> ANSI C translation phases ========================= +-------------------------------------------------+ | map physical characters to source character set | | replace line terminators with newlines | | decode trigraph sequences | +-------------------------------------------------+ | V +---------------------------------------+ | join lines along trailing backslashes | +---------------------------------------+ | V +-------------------------------------------------------------+ | decompose into preprocessing tokens and whitespace/comments | | strip comments | | retain newlines | +-------------------------------------------------------------+ | V +------------------------------------------------+ | execute preprocessing directives/invoke macros | | process included files | +------------------------------------------------+ | V +----------------------------------------------------------------+ | decode escape sequences in character constants/string literals | +----------------------------------------------------------------+ | V +--------------------------------------+ | concatenate adjacent string literals | +--------------------------------------+ | V +------------------------------------------+ | convert preprocessing tokens to C tokens | | analyze and translate tokens | +------------------------------------------+ | V +-----------------------------+ | resolve external references | | link libraries | | build program image | +-----------------------------+ </code></pre>
32,548,714
How to store and retrieve credentials on Windows using C#
<p>I build a C# program, to be run on Windows&nbsp;10. I want to send emails from this program (calculation results) by just pressing a button. I put the <code>from:</code> e-mail address and the <code>subject:</code>, etc. in C# properties, but I do not want to put a clear text password anywhere in the program, AND I don't want the user to have to type in the password for the server each time a mail is sent.</p> <p>Can that be done?</p> <p>If so, how (generally)?</p> <p>I was thinking of putting all that e-mail information, including an encrypted password for the server in a data file to be read during startup of the program.</p> <p>Or maybe Windows&nbsp;10 has a facility for that...</p>
32,550,674
1
1
null
2015-09-13 10:30:19.177 UTC
15
2019-05-30 11:55:35.727 UTC
2019-05-30 11:45:12.117 UTC
null
63,550
null
3,360,864
null
1
23
c#|credentials|credential-manager
31,359
<p>You can use the Windows Credential Management API. This way you will ask the user for the password only once and then store the password in Windows Credentials Manager.</p> <p>Next time your application starts and it needs to use the password it will read it from Windows Credentials Manager. One can use the Windows Credential Management API directly using <a href="http://en.wikipedia.org/wiki/Platform_Invocation_Services" rel="noreferrer">P/Invoke</a> (<a href="http://www.pinvoke.net/default.aspx/advapi32.credwrite" rel="noreferrer">credwrite</a>, <a href="http://www.pinvoke.net/default.aspx/advapi32/CredRead%20.html" rel="noreferrer">CredRead</a>, <a href="https://stackoverflow.com/questions/22435561/encrypting-credentials-in-a-wpf-application">example here</a>) or via a C# wrapper <a href="https://www.nuget.org/packages/CredentialManagement" rel="noreferrer">CredentialManagement</a>.</p> <hr> <p>Sample usage using the NuGet CredentialManagement package:</p> <pre><code>public class PasswordRepository { private const string PasswordName = "ServerPassword"; public void SavePassword(string password) { using (var cred = new Credential()) { cred.Password = password; cred.Target = PasswordName; cred.Type = CredentialType.Generic; cred.PersistanceType = PersistanceType.LocalComputer; cred.Save(); } } public string GetPassword() { using (var cred = new Credential()) { cred.Target = PasswordName; cred.Load(); return cred.Password; } } } </code></pre> <p>I don't recommend storing passwords in files on client machines. Even if you encrypt the password, you will probably embed the decryption key in the application code which is not a good idea.</p>
6,175,209
Low-latency IPC between C++ and Java
<p>What is the best way to implement C++/Java IPC for the following situation?</p> <p>(Someone recently asked a <a href="https://stackoverflow.com/questions/5900887/ipc-between-java-and-c-applications">similar question</a>, but my requirements are more specific)</p> <ol> <li><p>I have two programs -- one written in C++, the other in Java -- that need to communicate with each other. Both are running on the same machine.</p></li> <li><p>The programs send messages to each other. Messages are typically short (less than a few hundred bytes), but could potentially be 100KB or more in size.</p></li> <li><p>Messages do not need to be acknowledged (i.e., not a request/response model like HTTP). For example, the C++ program sends a message to the Java program, and the Java program may reply by sending a message to the C++ program at a later time -- and vice versa.</p></li> <li><p>An ideal solution would have a) very low latency, b) no security hassles (user does not have to authorize ports to be opened etc.) and c) will be platform-agnostic.</p></li> </ol> <p>My first thought was using <strong>sockets</strong> -- each program would act as a server to the other. Sockets have more overhead than other forms of IPC, and I don't know how the server would inform the client of the port number if I let the system auto-assign port numbers. I've also considered <strong>named pipes</strong>, but they are not supported (at least not consistently) across different platforms. <strong>JNI</strong> looks like an option, but can it cross process boundaries?</p> <p>Any suggestions?</p> <p>Thanks! </p> <p><strong>FOLLOW-UP QUESTIONS</strong></p> <ol> <li>If I go with sockets, would I need to open <em>two</em> sockets to allow for asynchronous communication as described above? </li> </ol>
6,175,264
6
1
null
2011-05-30 10:37:55.297 UTC
10
2011-05-30 11:31:15.137 UTC
2017-05-23 12:17:17.41 UTC
null
-1
null
67,063
null
1
13
java|c++|sockets|java-native-interface|ipc
14,397
<p>I'd suggest you to use <strong>TCP sockets</strong>.</p> <p>The actual overhead of TCP sockets, as of my experience, is very very low compared to the other tasks' workload of the applications, at least the ones I use to develop. I mean, sometimes even if sockets' latency is twice as the latency of other IPC mechanisms, in the overall workflow they have very little impact. And it saves you the hassle of making IPC between a Java application and a C++ one, that will eventually require you to use a specific Java library that uses JNI, with the overhead of JNI and the one of the library itself.</p> <p>I've actually measured, in my Java applications, that Garbage Collector impact is far more important than the latency caused by "<em>loopback</em>" TCP sockets.</p> <p>Moreover, TCP sockets are more scalable (and portable!) than traditional IPC. What if in the future you'll have to run the client and the server on different machines? In the 'TCP sockets' scenario, you'll have to do a 5-minute hack, in the 'traditional IPC' scenario, you'll have to rewrite the whole IPC stuff.</p> <p><strong>However, what is the general workflow of your application?</strong></p> <p>Even if the acknowledgement is not required, I'd suggest to use TCP (and not UDP) to avoid unsorted delivery (which leads to pain in the ass when it comes to rearrange the stuff you received - some of your messages are 100KB and this doesn't fit in a UDP packet).</p> <p>In reply to your last question, for the server to inform the client about the port, you can just make the server launch the client with a specific 'port' command line parameter, or make the server save a small file under /tmp (or another temporary directory) with the port number written inside.</p>
5,745,506
vim "modifiable" is off
<p>I am trying to create a new file with NERDTree. I hit the <kbd>a</kbd> key to create a new file and I get the message:</p> <p><code>E21: Cannot make changes, 'Modifiable' is off</code></p> <p>I'm using MacVim with Janus (almost out of the box).</p>
9,706,469
7
1
null
2011-04-21 14:30:49.82 UTC
27
2022-03-22 23:26:59.127 UTC
2022-03-22 23:26:59.127 UTC
null
241,142
null
157,503
null
1
176
vim|vi|macvim|nerdtree
116,646
<pre><code>:set ma </code></pre> <p>which is short for </p> <pre><code>:set modifiable </code></pre> <p>will make a buffer modifiable. And</p> <pre><code>:set noma </code></pre> <p>does the opposite.</p>
46,538,484
How can I implement a queue using Rxjs?
<p>With promises, it's really easy to implement a queue to prevent for example multiple HTTP requests from running in parallel:</p> <pre><code>class Runner { private promise; constructor(http) { this.promise = q.resolve(); } getUrl() { return this.promise = this.promise.then(() =&gt; http.get('http://someurl')) } } var runner = new Runner(http); var lastPromise; for (var i = 0; i &lt; 10; i++) { lastPromise = runner.getUrl(); } lastPromise.then(() =&gt; console.log("job's done!"); </code></pre> <p>I can't figure out how to do this in Rxjs tho. If I try something similar to the above, all previous HTTP calls get repeated when I add a request because it just adds to the stream and reruns the whole thing.</p> <p>I read something about a queue scheduler, but that doesn't seem to exist (anymore)?</p>
46,539,032
2
1
null
2017-10-03 06:37:17.197 UTC
8
2022-01-26 10:58:45.113 UTC
2021-11-29 16:35:38.503 UTC
null
542,251
null
1,001,966
null
1
11
rxjs
12,522
<p>You can use concat like @cartant suggested: </p> <pre class="lang-js prettyprint-override"><code>const urlQueue = Observable.fromPromise(http.get('http://someurl')) .concat(Observable.fromPromise(http.get('http://someurl'))) .concat(Observable.fromPromise(http.get('http://someurl'))); </code></pre> <p>But you would need to construct such a stream before subscribing and letting the queue handle it. Also; <code>fromPromise</code> is still eager so your promises will all start running directly when you invoke above code. To solve this you would need to use <a href="http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-defer" rel="noreferrer"><code>Defer()</code></a>:</p> <pre class="lang-js prettyprint-override"><code>const urls = [ 'http://someurl', 'http://someurl', 'http://someurl', ]; const queue = urls .map(url =&gt; Observable.defer(() =&gt; http.get(url)) .reduce((acc, curr) =&gt; acc.concat(curr)); </code></pre> <p>This approach uses the native array <code>map</code> to convert the urls to Observables and then uses <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce" rel="noreferrer"><code>reduce</code></a> to concat them all together into one big stream. </p> <p>A better solution would be to get your url's into a stream and then use <a href="http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-mergeMap" rel="noreferrer"><code>mergeMap</code></a> with a concurrency appended to it:</p> <pre class="lang-js prettyprint-override"><code>const urls = [ 'http://someurl', 'http://someurl', 'http://someurl', ]; const queuedGets = Observable.from(urls) .mergeMap(url =&gt; http.get(url), null, 1); </code></pre> <p>This will result in the urls being retrieved one by one after the previous one has completed but you still need to have all urls ready before starting. Depending on your usecase this might suffice. Note that a <code>mergeMap</code> with concurrency set to <code>1</code> is the equivalent of just using <code>concatMap</code></p> <p>The last part of the puzzle maybe is that you need to push new urls into your queue in your own tempo. To do so you would need a <a href="http://reactivex.io/rxjs/manual/overview.html#subject" rel="noreferrer">Subject</a></p> <blockquote> <p>A Subject is like an Observable, but can multicast to many Observers. Subjects are like EventEmitters: they maintain a registry of many listeners.</p> </blockquote> <pre class="lang-js prettyprint-override"><code>class HttpGetQueue { const queue = new Subject(); constructor() { public results = queue .mergeMap(url =&gt; http.get(url), null, 1); } addToQueue(url) { queue.next(url); } } const instance = new HttpGetQueue(); instance.results.subscribe(res =&gt; console.log('got res: ' + res); instance.addToQueue('http://someurl'); instance.addToQueue('http://someurl'); instance.addToQueue('http://someurl'); </code></pre>
39,284,607
How to implement a regex for password validation in Swift?
<p>I want to implement a regex validaton for passwords in Swift? I have tried the following regex, but not successful</p> <pre><code>([(0-9)(A-Z)(!@#$%ˆ&amp;*+-=&lt;&gt;)]+)([a-z]*){6,15} </code></pre> <p>My requirement is as follows: Password must be more than 6 characters, with at least one capital, numeric or special character</p>
39,288,484
6
2
null
2016-09-02 05:02:10.277 UTC
41
2022-04-29 06:10:07.217 UTC
2019-05-28 12:00:20.82 UTC
null
2,223,492
null
2,223,492
null
1
52
ios|swift|regex|validation
61,659
<p>The regex is</p> <pre><code>(?:(?:(?=.*?[0-9])(?=.*?[-!@#$%&amp;*ˆ+=_])|(?:(?=.*?[0-9])|(?=.*?[A-Z])|(?=.*?[-!@#$%&amp;*ˆ+=_])))|(?=.*?[a-z])(?=.*?[0-9])(?=.*?[-!@#$%&amp;*ˆ+=_]))[A-Za-z0-9-!@#$%&amp;*ˆ+=_]{6,15} </code></pre>
49,553,489
In cypress, how do I wait for a page to load?
<p>Don't tell anyone, but our app is not yet single-page. I can <a href="https://docs.cypress.io/api/commands/wait.html#Alias" rel="noreferrer">wait on a given XHR request</a> by giving the route an alias, but <strong>how do I wait until some navigation completes and the browser is safely on a new page?</strong></p>
49,617,422
2
1
null
2018-03-29 10:15:59.75 UTC
7
2021-06-29 00:19:19.567 UTC
null
null
null
null
1,585,345
null
1
33
cypress
54,467
<p>You can add some assert inside:</p> <pre class="lang-js prettyprint-override"><code>cy.click('#someButtonToNavigateOnNewPage'); cy.location('pathname', {timeout: 60000}) .should('include', '/newPage'); cy.click('#YouAreOnNewPage'); </code></pre> <p>You can change default timeout - by default it's 4000 ms (4 secs) - to ensure that user navigated the page. I've put a big number here - 60,000 ms - because I'm sure that 99% of users will leave if they do not have page loaded after 1 min. </p>
25,032,923
php warning fclose() expects parameter 1 to be resource boolean given
<p>I use newrelic to keep track of anything on my website and I always get this error:</p> <blockquote> <p>Error message: E_WARNING: fclose() expects parameter 1 to be resource, boolean given Stack trace: in fclose called at /etc/snmp/bfd-stats.php (68)</p> </blockquote> <p>This is how <code>/etc/snmp/bfd-stats.php</code> looks like</p> <pre><code>&lt;?php $a = 0; $ptr = 0; $any = 0; $mx = 0; $ns = 0; $cname = 0; $soa = 0; $srv = 0; $aaaa = 0; $txt = 0; $total = 0; if(file_exists('/etc/snmp/bfd-log-pos.stat')) { $lfh = fopen('/etc/snmp/bfd-log-pos.stat','r'); $string = fread($lfh,2087); $res = explode(',',$string); fclose($lfh); } else { $res = array(); $res[0] = 0; $res[1] = 0; } if(file_exists("/var/log/bfd_log.1")) { $stats = stat('/var/log/bfd_log.1'); if($stats[10] &gt; $res[0]) { $res[0] = 0; $res[1] = 0; } } $fh = fopen('/var/log/bfd_log', 'r'); fseek($fh,$res[1]); $blocks = 0; if(!$fh) { echo "Error! Couldn't open the file."; } else { while (!feof($fh)) { $data = fgets($fh); if(preg_match('/executed\sban/',$data)) { $blocks++; } } } $lfh = fopen('/etc/snmp/bfd-log-pos.stat','w'); $timestamp = time(); $pos = ftell($fh); fwrite($lfh,"$timestamp,$pos"); fclose($lfh); if(!fclose($fh)) { echo "Error! Couldn't close the file."; } print("bfd_blocks\n$blocks"); ?&gt; </code></pre> <p>On line 40: <code>$fh = fopen('/var/log/bfd_log', 'r');</code> I looked at the directory <code>/var/log</code> and there is no file called <code>bfd_log</code>, I dont know if I have to create it by myself or it is automatically created.</p> <p>Can anyone help me on fixing this error, Thanks in advance.</p>
25,033,232
3
1
null
2014-07-30 09:13:16.467 UTC
2
2020-03-19 19:05:00.967 UTC
2014-07-30 10:33:45.877 UTC
null
3,859,027
null
3,005,104
null
1
5
php|file-io|warnings
45,313
<p>The error indicates that you are trying to pass a variable with a boolean value (true/false) to a function that needs a resource instead of a boolean value.</p> <p>Please make sure that before you use resources from variables, the function that returns the resource has not run into trouble. Only on success perform the other functions that use this resource/variable.</p> <pre><code>$fh = fopen('/var/log/bfd_log', 'r'); // check fh before other functions use this variable if (!$fh) { echo "Error! Couldn't open the file."; } else { // perform task with resource $fh fseek($fh, $res[1]); [...] $lfh = fopen('/etc/snmp/bfd-log-pos.stat', 'w'); // check before other code block is executed and use this variable if( $lfh ) { // perform task with resource $lfh $pos = ftell($fh); fwrite($lfh, "$timestamp,$pos"); fclose($lfh); fclose($fh); [...] } else { // lfh error } } </code></pre> <p>If you always check before using variables, you won't run into this error anymore.</p>
42,209,758
How to use SaSS for an ASP.NET MVC application?
<h2>Problem and question</h2> <p>I've always had problems with CSS code, so now I always use SaSS code. But my question is: how can I use SaSS for an ASP.NET MVC application?</p> <p><a href="https://cloud.githubusercontent.com/assets/16222780/22893413/ecb2f00c-f215-11e6-8d90-52930964b6ad.gif" rel="noreferrer"><img src="https://cloud.githubusercontent.com/assets/16222780/22893413/ecb2f00c-f215-11e6-8d90-52930964b6ad.gif" alt=""></a></p> <h2>I've tried</h2> <p>I've tried tried to use a Gulp task for this. I've used these commands</p> <pre class="lang-shell prettyprint-override"><code>npm init npm install --save gulp npm install --save gulp-sass </code></pre> <p>Here is my <code>package.json</code> file:</p> <pre class="lang-json prettyprint-override"><code>{ "name": "markeonline", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" &amp;&amp; exit 1" }, "author": "Hein Pauwelyn", "license": "ISC", "dependencies": { "gulp": "^3.9.1", "gulp-sass": "^3.1.0" } } </code></pre> <p>Here is the <code>gulpfile.js</code></p> <pre class="lang-js prettyprint-override"><code>var gulp = require("gulp"), sass = require("gulp-sass"); // other content removed gulp.task("sass", function () { return gulp.src('./**/*.scss') .pipe(sass()) .pipe(gulp.dest(project.webroot + './MarkeOnline.Website/Content/css')); }); </code></pre> <p>Here is my project structure:</p> <p><a href="https://i.stack.imgur.com/VsdaC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VsdaC.png" alt="Solution explorer at Visual Studio"></a></p> <p>This code gives me the following error if I use the command below:</p> <pre class="lang-shell prettyprint-override"><code>gulp sass </code></pre> <blockquote> <p><strong>ReferenceError:</strong> project is not defined</p> <pre class="lang-none prettyprint-override"><code>[17:50:58] ReferenceError: project is not defined at Gulp.&lt;anonymous&gt; (D:\Documenten\Howest\Semester 4\05 - Project\MarkeOnlinebis\Project Execution\MarkeOnline\gulpfile.js:9:23) at module.exports (D:\Documenten\Howest\Semester 4\05 - Project\MarkeOnlinebis\Project Execution\MarkeOnline\node_modules\orchestrator\lib\runTask.js:34:7) at Gulp.Orchestrator._runTask (D:\Documenten\Howest\Semester 4\05 - Project\MarkeOnlinebis\Project Execution\MarkeOnline\node_modules\orchestrator\index.js:273:3) at Gulp.Orchestrator._runStep (D:\Documenten\Howest\Semester 4\05 - Project\MarkeOnlinebis\Project Execution\MarkeOnline\node_modules\orchestrator\index.js:214:10) at Gulp.Orchestrator.start (D:\Documenten\Howest\Semester 4\05 - Project\MarkeOnlinebis\Project Execution\MarkeOnline\node_modules\orchestrator\index.js:134:8) at C:\Users\hein_\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:129:20 at _combinedTickCallback (internal/process/next_tick.js:67:7) at process._tickCallback (internal/process/next_tick.js:98:9) at Module.runMain (module.js:592:11) at run (bootstrap_node.js:394:7) events.js:160 throw er; // Unhandled 'error' event ^ Error: node_modules\node-sass\test\fixtures\depth-first\_vars.scss Error: Undefined variable: "$import-counter". on line 1 of node_modules/node-sass/test/fixtures/depth-first/_vars.scss &gt;&gt; $import_counter: $import_counter + 1; -----------------^ at options.error (D:\Documenten\Howest\Semester 4\05 - Project\MarkeOnlinebis\Project Execution\MarkeOnline\node_modules\node-sass\lib\index.js:291:26) </code></pre> </blockquote>
42,209,949
3
1
null
2017-02-13 17:14:52.813 UTC
12
2019-04-25 17:30:10.613 UTC
2019-04-23 19:44:03.807 UTC
null
436,341
null
4,551,041
null
1
35
asp.net-mvc|sass|gulp
41,179
<p>Try <a href="https://marketplace.visualstudio.com/items?itemName=MadsKristensen.WebCompiler" rel="noreferrer">Web Compiler</a> plugin instead this is what I use to compile SCSS in MVC.</p> <blockquote> <p>A Visual Studio extension that compiles LESS, Sass, JSX, ES6 and CoffeeScript files.</p> </blockquote>
32,657,516
How to properly export an ES6 class in Node 4?
<p>I defined a class in a module:</p> <pre><code>"use strict"; var AspectTypeModule = function() {}; module.exports = AspectTypeModule; var AspectType = class AspectType { // ... }; module.export.AspectType = AspectType; </code></pre> <p>But I get the following error message:</p> <pre><code>TypeError: Cannot set property 'AspectType' of undefined at Object.&lt;anonymous&gt; (...\AspectType.js:30:26) at Module._compile (module.js:434:26) .... </code></pre> <p>How should I export this class and use it in another module? I have seen other SO questions, but I get other error messages when I try to implement their solutions.</p>
32,657,982
9
1
null
2015-09-18 17:08:24.213 UTC
30
2019-07-19 07:42:02.487 UTC
2018-12-01 02:06:44.857 UTC
null
212,378
null
520,957
null
1
146
javascript|node.js|module|export
306,812
<p>If you are using ES6 in Node 4, you cannot use ES6 module syntax without a transpiler, but CommonJS modules (Node's standard modules) work the same.</p> <pre><code>module.export.AspectType </code></pre> <p>should be</p> <pre><code>module.exports.AspectType </code></pre> <p>hence the error message "Cannot set property 'AspectType' of undefined" because <code>module.export === undefined</code>.</p> <p>Also, for</p> <pre><code>var AspectType = class AspectType { // ... }; </code></pre> <p>can you just write</p> <pre><code>class AspectType { // ... } </code></pre> <p>and get essentially the same behavior.</p>
9,037,108
Android - How to draw an arc based gradient
<p>I am trying to create an arc (variable number of degrees) that gradually goes from one color to another. From example from blue to red:<br><br> <img src="https://i.stack.imgur.com/ozRJN.jpg" alt="enter image description here"></p> <p>This is my code:</p> <pre><code>SweepGradient shader = new SweepGradient(center.x, center.y, resources.getColor(R.color.startColor),resources.getColor(R.color.endColor)); Paint paint = new Paint() paint.setStrokeWidth(1); paint.setStrokeCap(Paint.Cap.FILL); paint.setStyle(Paint.Style.FILL); paint.setShader(shader); canvas.drawArc(rectF, startAngle, sweepAngle, true, paint); </code></pre> <p>But the result is the entire arc is painted with the same color.</p> <p><strong>Edit:</strong><br> After more experimenting, I found out that the color spread is determined by the angle of the arc. If I draw an arc with a small angle, only the first color is displayed. The larger the angle, more colors are drawn. If the angle is small it seems that there is no gradient. <br>Here is an example. I am drawing 4 arcs - 90, 180, 270 and 360:</p> <pre><code>RectF rect1 = new RectF(50, 50, 150, 150); Paint paint1 = new Paint(); paint1.setStrokeWidth(1); paint1.setStrokeCap(Paint.Cap.SQUARE); paint1.setStyle(Paint.Style.FILL); SweepGradient gradient1 = new SweepGradient(100, 100, Color.RED, Color.BLUE); paint1.setShader(gradient1); canvas.drawArc(rect1, 0, 90, true, paint1); RectF rect2 = new RectF(200, 50, 300, 150); Paint paint2 = new Paint(); paint2.setStrokeWidth(1); paint2.setStrokeCap(Paint.Cap.SQUARE); paint2.setStyle(Paint.Style.FILL); SweepGradient gradient2 = new SweepGradient(250, 100, Color.RED, Color.BLUE); paint2.setShader(gradient2); canvas.drawArc(rect2, 0, 180, true, paint2); RectF rect3 = new RectF(50, 200, 150, 300); Paint paint3 = new Paint(); paint3.setStrokeWidth(1); paint3.setStrokeCap(Paint.Cap.SQUARE); paint3.setStyle(Paint.Style.FILL); SweepGradient gradient3 = new SweepGradient(100, 250, Color.RED, Color.BLUE); paint3.setShader(gradient3); canvas.drawArc(rect3, 0, 270, true, paint3); RectF rect4 = new RectF(200, 200, 300, 300); Paint paint4 = new Paint(); paint4.setStrokeWidth(1); paint4.setStrokeCap(Paint.Cap.SQUARE); paint4.setStyle(Paint.Style.FILL); SweepGradient gradient4 = new SweepGradient(250, 250, Color.RED, Color.BLUE); paint4.setShader(gradient4); canvas.drawArc(rect4, 0, 360, true, paint4); </code></pre> <p>And here is the result:</p> <p><img src="https://i.stack.imgur.com/4VsFW.png" alt="enter image description here"></p> <p>This is surprising because I'd expect the RED to be at the start of the arc, the BLUE at the end and enything between to be spread evenly regardless of angle. <br> I tried to space the colors manually using the positions parameter but the results were the same:</p> <pre><code>int[] colors = {Color.RED, Color.BLUE}; float[] positions = {0,1}; SweepGradient gradient = new SweepGradient(100, 100, colors , positions); </code></pre> <p>Any idea how to solve this?</p>
9,054,550
4
0
null
2012-01-27 16:58:33.713 UTC
13
2021-05-09 15:14:21.087 UTC
2012-01-29 02:16:15.863 UTC
null
445,117
null
445,117
null
1
26
android|graphics|2d|geometric-arc
20,840
<p>The solution for this is to set the position of BLUE. This is done like so:</p> <pre><code>int[] colors = {Color.RED, Color.BLUE}; float[] positions = {0,1}; SweepGradient gradient = new SweepGradient(100, 100, colors , positions); </code></pre> <p>The problem here is that when setting the position of BLUE to '1' this does not mean that it will be positioned at the end of the drawn arc, but instead at the end of the circle of which the arc is part of. To solve this, BLUE position should take into account the number of degrees in the arc. So if I'm drawing an arc with X degrees, position will be set like so:</p> <pre><code>float[] positions = {0,Xf/360f}; </code></pre> <p>So if X is 90, the gradient will place BLUE at 0.25 of the circle:</p> <p><img src="https://i.stack.imgur.com/A12vr.png" alt="enter image description here"></p>
9,576,843
using images inside <button> element
<p>I am trying to include an image and some text inside a button element. My code is as follows:</p> <pre><code>&lt;button class="testButton1"&gt;&lt;img src="Car Blue.png" alt=""&gt;Car&lt;/button&gt; </code></pre> <p>The CSS is:</p> <pre><code>.testButton1 { font-size:100%; height:10%; width: 25% } .testButton1 img { height:80%; vertical-align:middle; } </code></pre> <p>What I would like to do is to position the image to the left edge of the button, and position the text either in the center or to the right. Using &amp;nbsp works, but is perhaps a bit crude. I have tried to surround the image and text with spans or divs and then positioning those, but that seems to mess things up.</p> <p>What appears to be happening is that anything inside the button tag (unless formatted) is positioned as one unit in the center of a wider button (not noticeable if button width is left to auto adjust as both items are side-by-side.</p> <p>Any help, as always, is appreciated. Thank you.</p>
9,576,921
4
0
null
2012-03-06 01:52:23.823 UTC
8
2012-03-06 04:24:40.94 UTC
null
null
null
null
910,100
null
1
27
html|css|button
100,128
<p><strong>Background Image Approach</strong></p> <p>You can use a background image and have full control over the image positioning.</p> <p>Working example: <a href="http://jsfiddle.net/EFsU8/">http://jsfiddle.net/EFsU8/</a></p> <pre><code>BUTTON { padding: 8px 8px 8px 32px; font-family: Arial, Verdana; background: #f0f0f0 url([url or base 64 data]); background-position: 8px 8px; background-repeat: no-repeat; }​ </code></pre> <p>A slightly "prettier" example: <a href="http://jsfiddle.net/kLXaj/1/">http://jsfiddle.net/kLXaj/1/</a></p> <p>And <a href="http://jsfiddle.net/kLXaj/2/">another example</a> showing adjustments to the button based on the <code>:hover</code> and <code>:active</code> states.</p> <p><strong>Child Element Approach</strong></p> <p>The previous example would work with an <code>INPUT[type="button"]</code> as well as <code>BUTTON</code>. The <code>BUTTON</code> tag is allowed to contain markup and is intended for situations which require greater flexibility. After re-reading the original question, here are several more examples: <a href="http://jsfiddle.net/kLXaj/5/">http://jsfiddle.net/kLXaj/5/</a> </p> <p>This approach automatically repositions image/text based on the size of the button and provides more control over the internal layout of the button.</p>
9,350,025
Filtering a data frame on a vector
<p>I have a data frame <code>df</code> with an ID column eg <code>A</code>,<code>B</code>,etc. I also have a vector containing certain IDs:</p> <pre><code>L &lt;- c("A", "B", "E") </code></pre> <p>How can I filter the data frame to get only the IDs present in the vector? Individually, I would use</p> <pre><code>subset(df, ID == "A") </code></pre> <p>but how do I filter on a whole vector?</p>
9,350,360
2
0
null
2012-02-19 14:26:48.993 UTC
11
2012-02-19 16:40:49.27 UTC
2012-02-19 16:40:49.27 UTC
null
203,420
null
1,169,210
null
1
33
r|dataframe|subset
62,859
<p>You can use the <code>%in%</code> operator:</p> <pre><code>&gt; df &lt;- data.frame(id=c(LETTERS, LETTERS), x=1:52) &gt; L &lt;- c("A","B","E") &gt; subset(df, id %in% L) id x 1 A 1 2 B 2 5 E 5 27 A 27 28 B 28 31 E 31 </code></pre> <p>If your IDs are unique, you can use <code>match()</code>:</p> <pre><code>&gt; df &lt;- data.frame(id=c(LETTERS), x=1:26) &gt; df[match(L, df$id), ] id x 1 A 1 2 B 2 5 E 5 </code></pre> <p>or make them the rownames of your dataframe and extract by row:</p> <pre><code>&gt; rownames(df) &lt;- df$id &gt; df[L, ] id x A A 1 B B 2 E E 5 </code></pre> <p>Finally, for more advanced users, and if speed is a concern, I'd recommend looking into the <code>data.table</code> package.</p>
9,597,410
List all developers on a project in Git
<p>Is it possible to list all users that contributed to a project (users that have done commits) in Git?</p> <p>Any additional statistics?</p>
9,597,462
9
0
null
2012-03-07 07:31:52.227 UTC
60
2022-01-25 18:44:54.837 UTC
2018-07-25 20:40:20.553 UTC
null
63,550
null
587,228
null
1
307
git
88,924
<p>To show all users &amp; emails, and the number of commits in the CURRENT branch:</p> <pre><code>git shortlog --summary --numbered --email </code></pre> <p>Or simply:</p> <pre><code>git shortlog -sne </code></pre> <p>To show users from <strong>all branches</strong> (not only the ones in the current branch) you have to add <code>--all</code> flag:</p> <pre><code>git shortlog -sne --all </code></pre>
9,386,930
REST API Authorization & Authentication (web + mobile)
<p>I've read about oAuth, Amazon REST API, HTTP Basic/Digest and so on but can't get it all into "single piece". This is probably the closest situation - <a href="https://stackoverflow.com/questions/3963877/creating-an-api-for-mobile-applications-authentication-and-authorization">Creating an API for mobile applications - Authentication and Authorization</a></p> <p>I would like to built API-centric website - service. So (in the beginning) I would have an API in center and <strong>website</strong> (PHP + MySQL) would connect via <strong>cURL</strong>, <strong>Android</strong> and <strong>iPhone</strong> via their network interfaces. So 3 main clients - 3 API keys. And any other developer could also develop via API interface and they would get their own API key. API actions would be accepted/rejected based on userLevel status, if I'm an admin I can delete anything etc., all other can manipulate only their local (account) data.</p> <p>First, authorization - should I use oAuth + xAuth or my some-kind-of-my-own implemenation (see <a href="http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/RESTAuthentication.html?r=9197" rel="noreferrer">http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/RESTAuthentication.html?r=9197</a>)? As I understand, on <strong>Amazon service user is == API user (have API key)</strong>. On my service I need to separate standard users/account (the one who registered on the website) and Developer Accounts (who should have their API key).</p> <p>So I would firstly need to <strong>authorize the API key</strong> and then <strong>Authenticate the user</strong> itself. If I use Amazon's scheme to check developer's API keys (authorize their app), which sheme should I use for user authentication?</p> <p>I read about getting a token via <code>api.example.org/auth</code> after (via <strong>HTTPS</strong>, HTTP Basic) posting my username and password and then forward it on every following request. How manage tokens if I'm logged in simultaneously on <strong>Android</strong> and a <strong>website</strong>? What about man-in-the-middle-attack if I'm using SSL only on first request (when username and password are transmitted) and just HTTP on every other? Isn't that a problem in this example <a href="https://stackoverflow.com/questions/8562223/password-protecting-a-rest-service">Password protecting a REST service?</a></p>
9,387,289
1
0
null
2012-02-21 23:26:06.477 UTC
115
2017-07-21 10:15:01.663 UTC
2017-05-23 12:18:13.777 UTC
null
-1
null
455,268
null
1
73
php|api|authentication|rest|authorization
58,644
<p>As allways, the best way to protect a key is not to transmit it. </p> <p>That said, we typically use a scheme, where every "API key" has two parts: A non-secret ID (e.g. 1234) and a secret key (e.g. byte[64]). </p> <ul> <li>If you give out an API key, store it (salted and hashed) in you service's database.</li> <li>If you give out user accounts (protected by password), store the passwords (salted and hashed) in your service's database</li> </ul> <p>Now when a consumer <strong>first</strong> accesses your API, to connect, have him </p> <ul> <li>Send a "username" parameter ("john.doe" not secret)</li> <li>Send a "APIkeyID" parameter ("1234", not secret)</li> </ul> <p>and give him back </p> <ul> <li>the salts from your database (In case one of the parameters is wrong, just give back some repeatable salt - eg. sha1(username+"notverysecret").</li> <li>The timestamp of the server</li> </ul> <p>The consumer should store the salt for session duration to keep things fast and smooth, and he should calculate and keep the time offset between client and server.</p> <p>The consumer should now calculate the salted hashes of API key and password. This way the consumer has the exact same hashes for password and API key, as what is stored in your database, but without anything seceret ever going over the wire.</p> <p>Now when a consumer <strong>subseqently</strong> accesses your API, to do real work, have him</p> <ul> <li>Send a "username" parameter ("john.doe" not secret)</li> <li>Send a "APIkeyID" parameter ("1234", not secret)</li> <li>Send a "RequestSalt" parameter (byte[64], random, not secret)</li> <li>Send a "RequestTimestamp" parameter (calculated from client time and known offset)</li> <li>Send a "RequestToken" parameter (hash(passwordhash+request_salt+request_timestamp+apikeyhash))</li> </ul> <p>The server should not accept timestamps more than say 2 seconds in the past, to make this safe against a replay attack.</p> <p>The server can now calculate the same hash(passwordhash+request_salt+request_timestamp+apikeyhash) as the client, and be sure, that </p> <ul> <li>the client knows the API key,</li> <li>the client knows the correct password</li> </ul>
52,078,853
Is it possible to update FileList?
<p>I have:</p> <pre><code>&lt;input type="file" id="f" name="f" onchange="c()" multiple /&gt; </code></pre> <p>Every time the user selects a file(s), I build a list of all the selected files by pushing each element of <code>f.files</code> to an array:</p> <pre><code>var Files = []; function c() { for (var i=0;i&lt;this.files.length;i++) { Files.push(this.files[i]); }; } </code></pre> <p>At form submit, <code>f.files</code> contains only the item(s) from the last select action, so I will need to update <code>f.files</code> with the list of <code>FileList</code> items I have accumulated:</p> <pre><code>const upload=document.getElementById("f"); upload.files = files; </code></pre> <p>But the second line gives:</p> <blockquote> <p>Uncaught TypeError: Failed to set the 'files' property on 'HTMLInputElement': The provided value is not of type 'FileList'.</p> </blockquote> <p>It is not happy that I am assigning it an array. How can I construct a <code>FileList</code> object from the list of <code>FileList</code> elements I have earlier collected?</p> <p>Side question: I thought Javascript uses dynamic types. Why is it complaining about the wrong type here?</p>
52,079,109
2
2
null
2018-08-29 13:39:22.403 UTC
18
2021-04-04 18:01:35.857 UTC
2018-08-29 14:03:27.873 UTC
null
936,293
null
936,293
null
1
37
javascript
40,131
<p>It's like you said</p> <blockquote> <p>Failed to set the 'files' property on 'HTMLInputElement': The provided value is not of type 'FileList'.</p> </blockquote> <p>you can only set the files with a FileList instance, unfortunately the FileList is not constructible or changeable, but there is a way to get one in a round about way</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>/** * @params {File[]} files Array of files to add to the FileList * @return {FileList} */ function FileListItems (files) { var b = new ClipboardEvent("").clipboardData || new DataTransfer() for (var i = 0, len = files.length; i&lt;len; i++) b.items.add(files[i]) return b.files } var files = [ new File(['content'], 'sample1.txt'), new File(['abc'], 'sample2.txt') ]; fileInput.files = new FileListItems(files) console.log(fileInput.files)</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input type="file" id="fileInput" multiple /&gt;</code></pre> </div> </div> </p> <p>doing this will trigger a change event, so you might want to toggle the change event listener on and off</p>
52,280,874
How to make Card component clickable?
<p>I use the Ant Design for my WebApp. For the <a href="https://ant.design/components/card/" rel="noreferrer">Card</a>, there's a hoverable prop that make the card seams clickable but there's no onClick prop. How do I make it really clickable?</p> <p>This is my Code:</p> <pre><code>import React, { Component } from 'react'; import { Card, Avatar, Icon, Button, Divider } from 'antd'; import EventDetailsDrawer from '../ui/EventDetailsDrawer'; const { Meta } = Card; class EventCard extends Component { render() { return ( &lt;div onClick={alert("Hello from here")}&gt; &lt;Card hoverable cover={&lt;img alt="example" src="https://assetsnffrgf-a.akamaihd.net/assets/m/1102015169/univ/art/1102015169_univ_lsr_lg.jpg" /&gt;} bodyStyle={{ marginBottom: "-5px" }} &gt; &lt;Meta //avatar={&lt;Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" /&gt;} avatar={&lt;Button type="primary" shape="circle-outline"&gt;{this.props.owner}&lt;/Button&gt;} title={this.props.title} description={this.props.descp} /&gt; &lt;Divider style={{ marginLeft: "0px" }}&gt;&lt;/Divider&gt; &lt;p&gt;&lt;Icon type="clock-circle" style={{ fontSize: "15px", color: "#1890FE" }} theme="outlined" /&gt;&lt;span style={{ marginLeft: "15px" }} /&gt;{this.props.date}&lt;/p&gt; &lt;p&gt;&lt;Icon type="environment" style={{ fontSize: "15px", color: "#1890FE" }} theme="outlined" /&gt;&lt;span style={{ marginLeft: "15px" }} /&gt;{this.props.location}&lt;/p&gt; &lt;/Card&gt; &lt;EventDetailsDrawer&gt;&lt;/EventDetailsDrawer&gt; &lt;/div&gt; ); } } export default EventCard </code></pre> <p>I try to make a dive (around the Card) clickable, but the Code runs immediately after the app is loaded, since I pack each card into a list item. How to make Card component clickable?</p> <p>Thanks for your answer :)</p>
52,281,005
8
2
null
2018-09-11 17:03:12.023 UTC
2
2022-02-24 19:05:30.09 UTC
null
null
null
null
10,183,816
null
1
9
reactjs|antd
41,722
<p>Notice that what you are attaching to the div's <code>onClick</code> listener is the value returned by <code>alert</code> and not actually a function that should be run whenever the div is clicked.</p> <p>Try changing this:</p> <pre><code>&lt;div onClick={alert("Hello from here")}&gt; </code></pre> <p>To this:</p> <pre><code>&lt;div onClick={() =&gt; alert("Hello from here")}&gt; </code></pre>
10,760,310
How to open a new file in vim in a new window
<p>Is there a way to open vim in a new shell window or tab? I'm used to doing <code>$ mate file</code>, which opens the file in a new window. </p> <p>I prefer having one 'central shell' where I issue commands and edit files in other windows or tabs, as necessary. How do people normally open vim files locally?</p>
10,760,514
6
1
null
2012-05-25 19:28:24.12 UTC
15
2022-03-07 23:04:36.97 UTC
2012-05-25 19:33:37.42 UTC
null
1,216,976
null
651,174
null
1
86
unix|vim
150,666
<p>Check out gVim. You can launch that in its own window. </p> <p>gVim makes it really easy to manage multiple open buffers graphically.</p> <p>You can also do the usual <code>:e</code> to open a new file, <kbd>CTRL</kbd>+<kbd>^</kbd> to toggle between buffers, etc...</p> <p>Another cool feature lets you open a popup window that lists all the buffers you've worked on.</p> <p>This allows you to switch between open buffers with a single click.</p> <p>To do this, click on the <em>Buffers</em> menu at the top and click the dotted line with the scissors. </p> <p><img src="https://i.stack.imgur.com/sckza.png" alt="enter image description here"></p> <p>Otherwise you can just open a new tab from your terminal session and launch vi from there. </p> <p>You can usually open a new tab from terminal with <kbd>CTRL</kbd>+<kbd>T</kbd> <strong>or</strong> <kbd>CTRL</kbd>+<kbd>ALT</kbd>+<kbd>T</kbd></p> <p>Once vi is launched, it's easy to open new files and switch between them. </p>
7,150,209
Mysql - How to alias a whole table in a left join
<p>I have a situation where a property table holds an address id (from the g_addresses table) and an applicant table <em>also</em> holds an address id from the g_addresses. I'd like to left join these together but select all the fields in the table.</p> <p>I know of using 'as' to make an alias for fields, but is there any way to produce an alias for a whole table?</p> <pre><code>SELECT * FROM (`reference`) LEFT JOIN `applicants` ON `applicants`.`id` = `reference`.`applicant_id` LEFT JOIN `g_people` applicant_person ON `applicant_person`.`id` = `applicants`.`person_id` LEFT JOIN `g_addresses` applicant_address ON `applicant_address`.`id` = `applicants`.`address_id` LEFT JOIN `properties` ON `properties`.`id` = `reference`.`property_id` LEFT JOIN `g_addresses` property_address ON `property_address`.`id` = `properties`.`address_id` WHERE `reference`.`id` = 4 </code></pre> <p>This produces a result containing only one address row and not both, The row that is returned is the row from the final join and not the one previously, indicating it is overwriting when it is returned.</p>
7,156,642
2
0
null
2011-08-22 16:00:24.447 UTC
2
2017-11-19 09:28:18.403 UTC
2017-11-19 09:28:18.403 UTC
null
4,370,109
null
906,235
null
1
12
mysql|sql|join|alias
54,446
<p>I don't think you should use masked references, like <code>*</code> or <code>`reference`.*</code>, in your case, because you may end up with a row set containing identical column names (<code>id</code>, <code>address_id</code>).</p> <p>If you want to pull all the columns from the joined tables, you should probably specify them individually in the SELECT clause and assign a unique alias to every one of them:</p> <pre><code>SELECT ref.`id` AS ref_id, ref.`…` AS …, … app.`id` AS app_id, … FROM `reference` AS ref LEFT JOIN `applicants` AS app ON app.`id` = ref.`applicant_id` LEFT JOIN `g_people` AS ape ON ape.`id` = app.`person_id` LEFT JOIN `g_addresses` AS apa ON apa.`id` = app.`address_id` LEFT JOIN `properties` AS pro ON pro.`id` = ref.`property_id` LEFT JOIN `g_addresses` AS pra ON pra.`id` = pro.`address_id` WHERE ref.`id` = 4 </code></pre>
7,606,071
How can I do OAuth request by open new window, instead of redirect user from current page?
<p>I have done OAuth authentication with Twitter and Facebook. Currently, with each of these site, my server redirect user to a specified URL (for example, <a href="http://api.twitter.com/oauth/authorize" rel="noreferrer">http://api.twitter.com/oauth/authorize</a> with Twitter), then receive authentication parameters by callback url.</p> <p>But by that way, the users get redirected out of my page (to Facebook or Twitter), and only returns after input correct username &amp; password. It's like the way <a href="http://techcrunch.com" rel="noreferrer">http://techcrunch.com</a> do it when a user try to tweet a post.</p> <p>I remember that in some site, I have seen that we can connect not by redirect user out, but open a popup window for user to input credentials instead. After authentication is completde, the pop-up closed, the main page refresh with new content.</p> <p>This could be a very simple task with javascript, but I still can't figure it out. I can open authentication URL in a pop-up window, but how to get the result &amp; update the main page?</p>
7,607,058
2
0
null
2011-09-30 04:50:04.523 UTC
29
2022-05-06 04:19:59.477 UTC
null
null
null
null
512,993
null
1
44
javascript|facebook|twitter|popup
22,361
<p>Assuming you're opening authentication url in a pop-up using <code>window.open()</code>, you can access parent window by using:</p> <pre><code>window.opener </code></pre> <p>and to <strong>reload</strong> parent window (from a pop-up) use:</p> <pre><code>window.opener.location.reload(); </code></pre> <p>This code should be served on url that you've set up as success callback url of oauth authorization.</p> <p>In general, the flow should be: </p> <ul> <li>open a pop-up with an authorization page (on twitter.com for example)</li> <li>after successfull authorization twitter redirects user to url given by you (it gets opened in the very same pop-up)</li> <li>the opener window gets reloaded (via <code>window.opener.location.reload()</code>)</li> <li>close the pop-up itself (using javascript is you want)</li> </ul>
19,220,442
JMX password read access issue
<p>When I try to use JMX to monitor an application like this:</p> <pre><code>java -Dcom.sun.management.jmxremote.port=9999 \ -Dcom.sun.management.jmxremote.authenticate=false \ -Dcom.sun.management.jmxremote.ssl=false \ JMX_tester </code></pre> <p>it tells me:</p> <pre><code>Error: Password file read access must be restricted: /usr/lib/jvm/java-7-oracle/jre/lib/management/jmxremote.password </code></pre> <p>Yet, when I use <code>chmod</code> to restrict the read access, it tells me:</p> <pre><code>Error: can't read password file </code></pre> <p>Am I going insane or something? How can I fix this?</p> <p>This is Ubuntu btw, with the latest oracle jdk </p>
19,220,583
2
1
null
2013-10-07 08:48:15.917 UTC
7
2022-08-12 09:23:18.563 UTC
2016-03-28 20:13:11.453 UTC
null
1,191,727
null
1,939,961
null
1
40
java|ubuntu|jmx
54,510
<p>Make sure the user you are using to run the java process have access to the file (owner/read permissions).</p> <p>Try:</p> <pre><code>chmod 600 jmxremote.password </code></pre> <p>Plus I suggest you'll make your own password file and run it with </p> <pre><code>-Dcom.sun.management.jmxremote.password.file=pwFilePath </code></pre> <p>All explained <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/management/agent.html">here</a>.</p>
3,690,919
A Reference on the layout and structure of GameBoy Color Roms?
<p>Does anyone have a reference or source about how GameBoy Color roms are laid out - where the data and code, what machine code instructions are used, how the clock works etc? I'm interested in perhaps building an emulator myself but I can't find any information about the roms' setup other than looking at them in a hex editor. I'm interested in roms in the <code>.gbc</code> file format.</p> <p>I can of course look at the <a href="http://imrannazar.com/GameBoy-Emulation-in-JavaScript:-The-CPU" rel="noreferrer">source of a working emulator</a>, but I'm interested in something a bit more high level than that while I'm starting off. </p> <hr> <p><strong>Edit:</strong> Here are a load of really good resources I found:</p> <ul> <li><a href="http://imrannazar.com/GameBoy-Emulation-in-JavaScript:-The-CPU" rel="noreferrer">A Emulator being built in javascript</a> with <a href="http://github.com/Two9A/jsGB" rel="noreferrer">more up to date source</a>.</li> <li><a href="http://www.devrs.com/gb/files/gbspec.txt" rel="noreferrer">"The PAN documents" a detailed spec of the gameboy</a></li> <li><strong><a href="http://meatfighter.com/gameboy/TheNintendoGameboy.pdf" rel="noreferrer">A more up to date and better version of the previous item, with loads of stuff. Best resource</a>.</strong></li> <li><a href="http://nemesis.lonestar.org/computers/tandy/software/apps/m4/qd/opcodes.html" rel="noreferrer">Standard Z80 opcodes</a></li> <li><a href="http://imrannazar.com/Gameboy-Z80-Opcode-Map" rel="noreferrer"><strong>All the opcodes in the Gameboy Z80</strong></a></li> <li><a href="http://www.z80.info/z80gboy.txt" rel="noreferrer">A list of opcodes changed/removed in the Gameboy</a></li> <li><a href="http://www.zilog.com/docs/z80/um0080.pdf" rel="noreferrer">Z80 user manual (useful for flags)</a></li> <li><a href="http://verhoeven272.nl/cgi-bin/FS?fruttenboel/Gameboy&amp;Gameboy+section&amp;GBtop&amp;GBsummary&amp;GBcontent" rel="noreferrer">Discussion of differences between Gameboy <strong>Color</strong> Z80 and 8080/Z80</a></li> <li><a href="http://verhoeven272.nl/fruttenboel/Gameboy/index.html" rel="noreferrer"><strong>Massive site dedicated to gameboy architecture (+GBA)</strong></a></li> <li><a href="http://meatfighter.com/gameboy/GBCPUman.pdf" rel="noreferrer">Another document on GBSpec, with timings</a></li> </ul> <p>Also, <a href="http://github.com/CRogers/GbcEmulator" rel="noreferrer">see the source for my currently developing project</a> and <a href="http://meatfighter.com/gameboy/" rel="noreferrer">this finished one in C# for the Gameboy Classic (more docs)</a></p>
5,366,717
1
2
null
2010-09-11 12:08:26.163 UTC
22
2018-03-10 00:52:19.247 UTC
2010-09-19 19:28:15.63 UTC
null
139,766
null
139,766
null
1
24
emulation|file-format|rom
17,223
<p>ROM header from 0x100 to 0x14F. Everything else is "the ROM" meaning instructions interlaced with data or whatnot.</p> <p><a href="https://web.archive.org/web/20141105020940/http://problemkaputt.de/pandocs.htm" rel="nofollow noreferrer">https://web.archive.org/web/20141105020940/http://problemkaputt.de/pandocs.htm</a></p> <p>The opcodes are custom designed to be like the Zilog Z80, but are not exactly like it, since the CPU die itself is different from that of a Z80 as well as the clock cycles and register F flags being entirely different.</p> <p>Snoop around in my code to find out the operations. <a href="https://github.com/grantgalitz/GameBoy-Online/blob/master/js/GameBoyCore.js" rel="nofollow noreferrer">https://github.com/grantgalitz/GameBoy-Online/blob/master/js/GameBoyCore.js</a> look at line 525 and below. The GameBoy Color emulator is in javascript FTW.</p> <p>And Imran's emulator is a bad source for looking up how the opcodes work, because his emulator still has many problems with getting the opcodes right. Look at gambatte's source code for the most accurate (accurate and "some more") depiction of how the console works.</p>
28,142,361
Change remote repository credentials (authentication) on Intellij IDEA 14
<p>I recently changed my Bitbucket password for security reasons. However, IntelliJ didn't update my repository to the new credentials, so it stops me from pulling/pushing anything to my repository. I am not using any plugins for this, just the integrated VCS operations inside the IDE.</p> <p>Every time I pull/push, this pops out:</p> <blockquote> <p>fatal: Authentication failed for '<a href="https://momothereal:[email protected]/team/repo.git/">https://momothereal:[email protected]/team/repo.git/</a></p> </blockquote> <p>Where <strong>xxxxxxxxxxxx</strong> is my old password. I think changing this remote address with the correct password would fix it, though I cannot find where to do so.</p>
37,959,112
28
2
null
2015-01-25 22:31:36.87 UTC
35
2022-08-04 06:47:27.173 UTC
2018-04-20 10:38:44.203 UTC
null
896,663
null
3,902,473
null
1
177
java|git|intellij-idea|bitbucket
264,226
<p>The easiest of all the above ways is to:</p> <ol> <li>Go to Settings>>Appearance &amp; Behavior>>System Settings>>Passwords</li> <li>Change the setting to not store passwords at all</li> <li>Invalidate and restart IntelliJ</li> <li>Go to Settings>>Version Control>>Git>>SSH executable: <strong>Build-in</strong></li> <li>Do a fetch/pull operation</li> <li>Enter the password when prompted</li> <li>Again go to Settings>>Appearance &amp; Behavior>>System Settings>>Passwords</li> <li>This time select store passwords on disk(protected with master password)</li> </ol> <p>Voila!</p> <p>Note that this will not work if your password is in your URL itself. If that is the case then you need to follow the steps given by @moleksyuk <a href="https://stackoverflow.com/a/33216283/896663">here</a></p> <p>You also choose to use the credentials helper option in IntelliJ to achieve similar functionality as suggested by Ramesh <a href="https://stackoverflow.com/a/59565351/896663">here</a></p>
1,937,601
convert string to date without time
<p>This line </p> <pre><code>System.DateTime.Parse("09/12/2009"); </code></pre> <p>convert date (string) to 9/12/2009 12:00:00 AM. How can I get a date in the form 9/12/2009.</p> <p>after explanations I do: </p> <pre><code>DateTime dt = System.DateTime.Parse(Request.Form["datepicker"]); dt.ToString("dd/mm/yyyy"); /* and this code have time, why???*/ </code></pre>
1,937,606
3
2
null
2009-12-21 00:19:10.777 UTC
2
2017-07-06 20:07:04.243 UTC
2017-07-06 19:17:37.867 UTC
null
3,792,634
null
214,544
null
1
14
c#|asp.net|asp.net-mvc
76,188
<p>Your problem is not with the parsing but with the output. Look at how <a href="http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm" rel="noreferrer">ToString</a> works for DateTime, or use this example:</p> <pre><code>using System; class Program { static void Main(string[] args) { DateTime dt = DateTime.Parse("09/12/2009"); Console.WriteLine(dt.ToString("dd/MM/yyyy")); } } </code></pre> <p>Or to get something in your locale:</p> <pre><code>Console.WriteLine(dt.ToShortDateString()); </code></pre> <p>Update: Your update to the question implies that you do not understand fully my answer yet, so I'll add a little more explanation. There is no Date in .NET - there is only DateTime. If you want to represent a date in .NET, you do so by storing the time midnight at the start of that day. The time must always be stored, even if you don't need it. You cannot remove it. The important point is that when you display this DateTime to a user, you only show them the Date part.</p>
2,121,896
Converting dates in AWK
<p>I have a file containing many columns of text, including a timestamp along the lines of <code>Fri Jan 02 18:23</code> and I need to convert that date into <code>MM/DD/YYYY HH:MM</code> format.</p> <p>I have been trying to use the standard `date' tool with awk getline to do the conversion, but I can't quite figure out how to pass the fields into the 'date' command in the format it expects (quoted with " or 's,) as getline needs the command string enclosed in quotes too.</p> <p>Something like <code>"date -d '$1 $2 $3 $4' +'%D %H:%M'" | getline var</code></p> <p>Now that I think about it, I guess what I'm really asking is how to embed awk variables into a string.</p>
2,122,020
3
0
null
2010-01-23 03:02:56.663 UTC
6
2019-01-10 16:55:48.257 UTC
2016-02-11 14:44:18.833 UTC
null
1,212,012
null
257,259
null
1
25
datetime|command-line|awk
48,487
<p>you can try this. Assuming just the date you specified is in the file</p> <pre><code>awk ' { cmd ="date \"+%m/%d/%Y %H:%M\" -d \""$1" "$2" "$3" "$4"\"" cmd | getline var print var close(cmd) }' file </code></pre> <p>output</p> <pre><code>$ ./shell.sh 01/02/2010 18:23 </code></pre> <p>and if you are not using GNU tools, like if you are in Solaris for example, use nawk</p> <pre><code>nawk 'BEGIN{ m=split("Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec",d,"|") for(o=1;o&lt;=m;o++){ months[d[o]]=sprintf("%02d",o) } cmd="date +%Y" cmd|getline yr close(cmd) } { day=$3 mth=months[$2] print mth"/"day"/"yr" "$4 } ' file </code></pre>
1,574,788
WPF Built-in Commands
<p>I'm looking for a complete list of built-in WPF Commands.</p> <p>The best list I've found so far is <a href="http://en.csharp-online.net/WPF_Concepts%E2%80%94Built-In_Commands" rel="noreferrer">here</a>, but it does not list all commands.</p> <p>Some nice-to-have details would be:</p> <ul> <li><p>Controls/components with support to the commands (for example, <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.textbox.aspx" rel="noreferrer">TextBox</a> supports edit commands such as Paste, Copy, Cut, Redo, and Undo);</p></li> <li><p>Default Key Gestures and UI Text (can be extracted from <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.applicationcommands.help.aspx" rel="noreferrer">MSDN Library</a>).</p></li> </ul>
1,691,082
3
0
2009-10-15 20:20:09.497 UTC
2009-10-15 20:20:09.497 UTC
25
2010-01-21 22:09:22.3 UTC
null
null
null
null
123,897
null
1
33
.net|wpf|command
22,243
<p>It is easy to display a complete list of all commands in all loaded assemblies:</p> <pre><code> public string[] GetAllCommands() { return ( from assembly in AppDomain.CurrentDomain.GetAssemblies() from type in assembly.GetTypes() from prop in type.GetProperties() where typeof(ICommand).IsAssignableFrom(prop.PropertyType) &amp;&amp; prop.GetAccessors()[0].IsStatic orderby type.Name, prop.Name select type.Name + "." + prop.Name ).ToArray(); } </code></pre> <p>With PresentationFramework loaded I get the list at the bottom of this answer, which you will see is absolutely complete.</p> <p>If you also want to see the command type (eg RoutedUIComand) and gestures, you can add this to the LINQ:</p> <pre><code> let commandType = prop.PropertyType let gestures = typeof(UIElement).IsAssignableFrom(commandType) ? ((UIElement)prop.GetValue(null)).InputGestures : null </code></pre> <p>Then your select might be something like this:</p> <pre><code> select type.Name + "." + prop.Name + " " + commandType.Name + " " + gestures </code></pre> <p>Programmatically finding out which controls do something with a given command is also possible. Basically something like this ought to work (not tried, but this will give you the idea):</p> <pre><code>var allCommands = ( from assembly in AppDomain.CurrentDomain.GetAssemblies() from type in assembly.GetTypes() from prop in type.GetProperties() where typeof(ICommand).IsAssignableFrom(prop.PropertyType) &amp;&amp; prop.GetAccessors()[0].IsStatic orderby type.Name, prop.Name select new { typeName = type.Name, propName = prop.Name, displayAs = type.Name + "." + prop.Name, } ).ToArray(); var classesReferencingCommand = ( from assembly in AppDomain.CurrentDomain.GetAssemblies() from type in assembly.GetTypes() from method in type.GetMethods() let methodBodyString = ConvertILToString(method.MethodBody.GetILAsByteArray()) let info = new { typeName = type.FullName, referencedCommands = from cmd in allCommands where methodBodyString.Contains(cmd.typeName) &amp;&amp; methodBodyString.Contains(cmd.propName) select cmd } where info.commands.Any() select info ).ToArray(); </code></pre> <p>where ConvertILToString would probably be something like this:</p> <pre><code>static string ConvertILToString(byte[] bytes) { return new string(bytes.Where(b =&gt; b!=0).Select(b =&gt; (char)b).ToArray()); } </code></pre> <p>The results can be used any way you like, for example they can be displayed using an ItemsControl:</p> <pre><code>&lt;ItemsControl Source="{Binding classesReferencingCommand}"&gt; &lt;ItemsControl.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;StackPanel&gt; &lt;TextBox Text="{Binding typeName}" FontWeight="Bold"&gt; &lt;ItemsControl Source="{Binding referencedCommands}" Margin="10 0 0 0"&gt; &lt;ItemsControl.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;TextBox Text="{Binding displayAs}" /&gt; ... close all tags ... </code></pre> <p>Alternatively you could output the data in a text or XML format or add it to a database. Also note that this second query can be turned around with the command iteration on the outside if you prefer a listing by command.</p> <p>The code above will give you the precise facts and will not lie, because it is looking at the NET Framework itself.</p> <p>Here is the promised list of all commands in PresentationFramework:</p> <pre><code>ApplicationCommands.CancelPrint ApplicationCommands.Close ApplicationCommands.ContextMenu ApplicationCommands.Copy ApplicationCommands.CorrectionList ApplicationCommands.Cut ApplicationCommands.Delete ApplicationCommands.Find ApplicationCommands.Help ApplicationCommands.New ApplicationCommands.NotACommand ApplicationCommands.Open ApplicationCommands.Paste ApplicationCommands.Print ApplicationCommands.PrintPreview ApplicationCommands.Properties ApplicationCommands.Redo ApplicationCommands.Replace ApplicationCommands.Save ApplicationCommands.SaveAs ApplicationCommands.SelectAll ApplicationCommands.Stop ApplicationCommands.Undo ComponentCommands.ExtendSelectionDown ComponentCommands.ExtendSelectionLeft ComponentCommands.ExtendSelectionRight ComponentCommands.ExtendSelectionUp ComponentCommands.MoveDown ComponentCommands.MoveFocusBack ComponentCommands.MoveFocusDown ComponentCommands.MoveFocusForward ComponentCommands.MoveFocusPageDown ComponentCommands.MoveFocusPageUp ComponentCommands.MoveFocusUp ComponentCommands.MoveLeft ComponentCommands.MoveRight ComponentCommands.MoveToEnd ComponentCommands.MoveToHome ComponentCommands.MoveToPageDown ComponentCommands.MoveToPageUp ComponentCommands.MoveUp ComponentCommands.ScrollByLine ComponentCommands.ScrollPageDown ComponentCommands.ScrollPageLeft ComponentCommands.ScrollPageRight ComponentCommands.ScrollPageUp ComponentCommands.SelectToEnd ComponentCommands.SelectToHome ComponentCommands.SelectToPageDown ComponentCommands.SelectToPageUp DocumentViewer.FitToHeightCommand DocumentViewer.FitToMaxPagesAcrossCommand DocumentViewer.FitToWidthCommand DocumentViewer.ViewThumbnailsCommand EditingCommands.AlignCenter EditingCommands.AlignJustify EditingCommands.AlignLeft EditingCommands.AlignRight EditingCommands.Backspace EditingCommands.CorrectSpellingError EditingCommands.DecreaseFontSize EditingCommands.DecreaseIndentation EditingCommands.Delete EditingCommands.DeleteNextWord EditingCommands.DeletePreviousWord EditingCommands.EnterLineBreak EditingCommands.EnterParagraphBreak EditingCommands.IgnoreSpellingError EditingCommands.IncreaseFontSize EditingCommands.IncreaseIndentation EditingCommands.MoveDownByLine EditingCommands.MoveDownByPage EditingCommands.MoveDownByParagraph EditingCommands.MoveLeftByCharacter EditingCommands.MoveLeftByWord EditingCommands.MoveRightByCharacter EditingCommands.MoveRightByWord EditingCommands.MoveToDocumentEnd EditingCommands.MoveToDocumentStart EditingCommands.MoveToLineEnd EditingCommands.MoveToLineStart EditingCommands.MoveUpByLine EditingCommands.MoveUpByPage EditingCommands.MoveUpByParagraph EditingCommands.SelectDownByLine EditingCommands.SelectDownByPage EditingCommands.SelectDownByParagraph EditingCommands.SelectLeftByCharacter EditingCommands.SelectLeftByWord EditingCommands.SelectRightByCharacter EditingCommands.SelectRightByWord EditingCommands.SelectToDocumentEnd EditingCommands.SelectToDocumentStart EditingCommands.SelectToLineEnd EditingCommands.SelectToLineStart EditingCommands.SelectUpByLine EditingCommands.SelectUpByPage EditingCommands.SelectUpByParagraph EditingCommands.TabBackward EditingCommands.TabForward EditingCommands.ToggleBold EditingCommands.ToggleBullets EditingCommands.ToggleInsert EditingCommands.ToggleItalic EditingCommands.ToggleNumbering EditingCommands.ToggleSubscript EditingCommands.ToggleSuperscript EditingCommands.ToggleUnderline MediaCommands.BoostBass MediaCommands.ChannelDown MediaCommands.ChannelUp MediaCommands.DecreaseBass MediaCommands.DecreaseMicrophoneVolume MediaCommands.DecreaseTreble MediaCommands.DecreaseVolume MediaCommands.FastForward MediaCommands.IncreaseBass MediaCommands.IncreaseMicrophoneVolume MediaCommands.IncreaseTreble MediaCommands.IncreaseVolume MediaCommands.MuteMicrophoneVolume MediaCommands.MuteVolume MediaCommands.NextTrack MediaCommands.Pause MediaCommands.Play MediaCommands.PreviousTrack MediaCommands.Record MediaCommands.Rewind MediaCommands.Select MediaCommands.Stop MediaCommands.ToggleMicrophoneOnOff MediaCommands.TogglePlayPause NavigationCommands.BrowseBack NavigationCommands.BrowseForward NavigationCommands.BrowseHome NavigationCommands.BrowseStop NavigationCommands.DecreaseZoom NavigationCommands.Favorites NavigationCommands.FirstPage NavigationCommands.GoToPage NavigationCommands.IncreaseZoom NavigationCommands.LastPage NavigationCommands.NavigateJournal NavigationCommands.NextPage NavigationCommands.PreviousPage NavigationCommands.Refresh NavigationCommands.Search NavigationCommands.Zoom Slider.DecreaseLarge Slider.DecreaseSmall Slider.IncreaseLarge Slider.IncreaseSmall Slider.MaximizeValue Slider.MinimizeValue </code></pre> <p>This list is complete.</p> <p>If there are any additional gestures in the themes, they can easily be extracted by loading the theme resource dictionary and doing some LINQ on it. The queries are trivial: Just search for <code>&lt;InputGesture&gt;</code>. <strong>Update:</strong> I don't think there are any gestures in the themes, since the default gestures are loaded from resources. So this part will probably not be necessary.</p>
8,369,708
Limiting the number of characters in a string, and chopping off the rest
<p>I need to create a summary table at the end of a log with some values that are obtained inside a class. The table needs to be printed in fixed-width format. I have the code to do this already, but I need to limit Strings, doubles and ints to a fixed-width size that is hard-coded in the code.</p> <p>So, suppose I want to print a fixed-width table with</p> <pre><code> int,string,double,string int,string,double,string int,string,double,string int,string,double,string and the fixed widths are: 4, 5, 6, 6. </code></pre> <p>If a value exceeds this width, the last characters need to be cut off. So for example:</p> <pre><code> 124891, difference, 22.348, montreal </code></pre> <p>the strings that need to be printed ought to be:</p> <pre><code> 1248 diffe 22.348 montre </code></pre> <p>I am thinking I need to do something in the constructor that forces a string not to exceed a certain number of characters. I will probably cast the doubles and ints to a string, so I can enforce the maximum width requirements.</p> <p>I don't know which method does this or if a string can be instantiated to behave taht way. Using the formatter only helps with the fixed-with formatting for printing the string, but it does not actually chop characters that exceed the maximum length.</p>
8,369,746
8
1
null
2011-12-03 18:00:44.42 UTC
12
2020-01-20 23:10:29.667 UTC
2011-12-03 18:10:17.68 UTC
null
213,269
null
487,980
null
1
79
java|string|substring
248,939
<p>Use this to cut off the non needed characters:</p> <pre><code>String.substring(0, maxLength); </code></pre> <p>Example:</p> <pre><code>String aString ="123456789"; String cutString = aString.substring(0, 4); // Output is: "1234" </code></pre> <p>To ensure you are not getting an IndexOutOfBoundsException when the input string is less than the expected length do the following instead:</p> <pre><code>int maxLength = (inputString.length() &lt; MAX_CHAR)?inputString.length():MAX_CHAR; inputString = inputString.substring(0, maxLength); </code></pre> <p>If you want your integers and doubles to have a certain length then I suggest you use <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/text/NumberFormat.html">NumberFormat</a> to format your numbers instead of cutting off their string representation. </p>
19,665,914
Bootstrap wysiwyg textarea editor working on Bootstrap 3
<p>I'm looking for a wysiwyg textarea editor for Bootstrap 3. Everything I can find on Google only works with Bootstrap 2. Has anybody an good, simple wysiwyg Edtor for Bootstrap 3?</p>
19,670,216
6
1
null
2013-10-29 18:06:12.847 UTC
4
2016-07-25 10:51:09.89 UTC
2014-01-17 00:22:42.843 UTC
null
76,456
null
2,535,457
null
1
20
android|css|html|twitter-bootstrap
71,726
<p>Thanks for the Tip of wysihtml5. I found a solution for Bootstrap 2 and wysihtml5: <a href="http://jhollingworth.github.io/bootstrap-wysihtml5/">bootstrap-wysihtml5</a>. I update it to Bootstrap 3: <a href="http://schnawel007.github.io/bootstrap3-wysihtml5/">bootstrap3-wysihtml5</a>.</p>
19,430,346
How can I tell if Python setuptools is installed?
<p>I'm writing a quick shell script to make it easier for some of our developers to run Fabric. (I'm also new to Python.) Part of installing Fabric is installing pip, and part of installing pip is installing setuptools.</p> <p>Is there any easy way to detect if setuptools is already installed? I'd like to make it possible to run the script multiple times, and it skip anything it's already done. As it stands now, if you run ez_setup.py twice in a row, you'll get a failure the second time.</p> <p>One idea I had was to look for the easy_install scripts under the /Scripts folder. I can guess at the Python root using sys.executable, and then swap off the executable name itself. But I'm looking for something a little more elegant (and perhaps cross-OS friendly). Any suggestions?</p>
19,430,450
7
1
null
2013-10-17 15:03:11.667 UTC
3
2020-05-28 13:27:21.107 UTC
null
null
null
null
1,272,885
null
1
18
python|pip|setuptools
69,266
<p>This isn't great but it'll work.</p> <p>A simple python script can do the check</p> <pre><code>import sys try: import setuptools except ImportError: sys.exit(1) else: sys.exit(0) </code></pre> <p>OR</p> <pre><code>try: import setuptools except ImportError: print("Not installed.") else: print("Installed.") </code></pre> <p>Then just check it's exit code in the calling script</p>
54,486,525
Tried to register two views with the same name RNGestureHandlerButton
<p>I try to create navigation with <code>{ createStackNavigator, createAppContainer }</code> from <code>react-navigation</code> but when a start my application I always get an error. I can't find any documentation or help on this.</p> <p>This is my <code>package.json</code>:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;main&quot;: &quot;node_modules/expo/AppEntry.js&quot;, &quot;scripts&quot;: { &quot;start&quot;: &quot;expo start&quot;, &quot;android&quot;: &quot;expo start --android&quot;, &quot;ios&quot;: &quot;expo start --ios&quot;, &quot;eject&quot;: &quot;expo eject&quot; }, &quot;dependencies&quot;: { &quot;expo&quot;: &quot;^32.0.0&quot;, &quot;react&quot;: &quot;16.5.0&quot;, &quot;react-native&quot;: &quot;github.com/expo/react-native/archive/sdk-32.0.0.tar.gz&quot;, &quot;react-native-gesture-handler&quot;: &quot;^1.0.15&quot;, &quot;react-navigation&quot;: &quot;^3.0.9&quot; }, &quot;devDependencies&quot;: { &quot;babel-preset-expo&quot;: &quot;^5.0.0&quot; }, &quot;private&quot;: true } </code></pre>
54,488,122
13
2
null
2019-02-01 20:08:24.28 UTC
5
2022-06-29 18:52:02.017 UTC
2022-05-29 19:14:37.37 UTC
null
584,676
null
3,362,330
null
1
17
react-native
49,130
<blockquote> <p>Note this answer was written for Expo v33. Please check with the current documentation for react-navigation and the version of Expo that you are using for up-to-date installation instructions.</p> </blockquote> <p>The reason for your error is that you are using <code>react-navigation</code> in your Expo app, however you have followed the tutorial incorrectly.</p> <p><a href="https://reactnavigation.org/docs/en/getting-started.html" rel="noreferrer">https://reactnavigation.org/docs/en/getting-started.html</a></p> <p>If you read the instructions it tells you that once you have installed <code>react-navigation</code> you should then install <code>react-native-gesture-handler</code>. However that is not what they say</p> <blockquote> <p>Next, install react-native-gesture-handler. If you’re using Expo you don’t need to do anything here, it’s included in the SDK.</p> </blockquote> <p>It says that if you are using <code>Expo</code> you do not need to install <code>react-native-gesture-handler</code> as it is already installed.</p> <p>You are getting errors because you have installed <code>react-native-gesture-handler</code>, it already exists in Expo, and Expo is getting confused about where to get its information from.</p> <p>To solve your problem do the following.</p> <ol> <li>Close all terminals running <code>Expo</code></li> <li>Close the browser window running <code>Expo</code></li> <li>Clear the project you were working on from the <code>Expo</code> app on your device.</li> <li>Delete your <code>package-lock.json</code></li> <li>Delete your <code>node_modules</code> folder</li> <li>Remove the <code>react-native-gesture-handler</code> entry from your <code>package.json</code></li> <li>Run <code>npm i</code></li> <li>Restart <code>Expo</code> using <code>expo start -c</code></li> </ol> <p>Be careful when using <code>Expo</code> it is easy to install dependencies that cannot run with it, and cause yourself issues like this.</p>
2,539,035
How to do a timestamp comparison with JPA query?
<p>We need to make sure only results within the last 30 days are returned for a JPQL query. An example follows:</p> <pre><code>Date now = new Date(); Timestamp thirtyDaysAgo = new Timestamp(now.getTime() - 86400000*30); Query query = em.createQuery( "SELECT msg FROM Message msg "+ "WHERE msg.targetTime &lt; CURRENT_TIMESTAMP AND msg.targetTime &gt; {ts, '"+thirtyDaysAgo+"'}"); List result = query.getResultList();</code></pre> <p>Here is the error we receive:</p> <pre>&lt;openjpa-1.2.3-SNAPSHOT-r422266:907835 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: An error occurred while parsing the query filter 'SELECT msg FROM BroadcastMessage msg WHERE msg.targetTime &lt; CURRENT_TIMESTAMP AND msg.targetTime > {ts, '2010-04-18 04:15:37.827'}'. Error message: org.apache.openjpa.kernel.jpql.TokenMgrError: Lexical error at line 1, column 217. Encountered: "{" (123), after : ""</pre> <p>Help!</p>
2,539,953
2
3
null
2010-03-29 15:15:56.367 UTC
2
2017-03-22 20:03:57.69 UTC
null
null
null
null
209,794
null
1
10
jpa|jpql|openjpa
60,403
<p>So the query you input is not JPQL (which you could see by referring to the JPA spec). If you want to compare a field with a Date then you input the Date as a parameter to the query</p> <pre><code>msg.targetTime &lt; CURRENT_TIMESTAMP AND msg.targetTime &gt; :param </code></pre> <p>THIS IS NOT SQL.</p>
42,166,837
What size screenshots should be used for IAPs ( In app purchases ) for Mac apps?
<p>What dimensions should be used for IAP screenshots for Mac apps on iTunesconnect?</p> <p>I have tried uploading PNG screenshots with:</p> <pre><code>2560 x 1600 px 640 x 920 px </code></pre> <p>to no avail... but the upload does not seem to be accepted... Can anyone advise which dimensions will be accepted? Apple specifies 640 x 920 but it does not upload and there is no error message.</p> <p><a href="https://i.stack.imgur.com/7mZrQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7mZrQ.png" alt="enter image description here"></a></p>
42,177,566
6
0
null
2017-02-10 19:03:59.587 UTC
10
2020-11-20 21:23:57.227 UTC
null
null
null
null
407,379
null
1
40
macos|in-app-purchase|app-store-connect|screenshot
14,089
<p>In the official docs I found this: </p> <blockquote> <p>A screenshot of the product as it appears on the device. This screenshot is used for Apple’s review only and is not displayed on the App Store. Screenshots requirements are outlined below: iOS: at least 640 x 920 pixels. tvOS requires 1920 x1080 pixels. <strong>macOS requires 1280 x 800 pixels.</strong></p> </blockquote> <p>Source: <a href="https://help.apple.com/app-store-connect/#/dev84b80958f" rel="nofollow noreferrer">https://help.apple.com/app-store-connect/#/dev84b80958f</a></p> <p>Interesting enough I just tried with a 640px (width) by 920px (height) screenshot for Mac IAP and everything is fine. Make sure you have no alpha-channel, but this gives another error.</p>
38,160,006
Google Maps error: Oops! Something went wrong. This page didn't load Google Maps correctly
<p>First time asking on stackoverflow, so be patient if I break some rule, tried my best to solve by myself searching for a solution, but had no luck. </p> <p>I used a tool to help me customize a google map with multiple markers location and styles (code below). I test it local and on my own domain and it's working good. When I publish it on the production site, it shows for a while then an error message appear </p> <blockquote> <p>"Oops! Something went wrong. This page didn't load Google Maps correctly. See the >JavaScript console for technical details"</p> </blockquote> <p>Javascript console on Firefox just report an error, I think not related: "API Fullscreen is deprecated"</p> <p>I tried also by getting a (new) API KEY from Google Developer Console and insert it in the API request link as described in Google documentation (no luck). I verified the ownership of the site on Google Search Console. Anyway I think this is not my case, cause domain is recent and console don't report any error about API KEY. </p> <p>Really wondering what's wrong. Here is a demo not working: <a href="http://www.fastdirectlink.com/map.html">http://www.fastdirectlink.com/map.html</a> Here is a demo working: <a href="http://tiikeridesign.com/map.html">http://tiikeridesign.com/map.html</a></p> <p>Here is the code I used </p> <pre><code>&lt;script src='https://maps.googleapis.com/maps/api/js?key=&amp;sensor=false&amp;extension=.js'&gt;&lt;/script&gt; &lt;script&gt; google.maps.event.addDomListener(window, 'load', init); var map; function init() { var mapOptions = { center: new google.maps.LatLng(45.0735671,7.67406040000003), zoom: 2, zoomControl: true, zoomControlOptions: { style: google.maps.ZoomControlStyle.DEFAULT, }, disableDoubleClickZoom: false, mapTypeControl: true, mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR, }, scaleControl: true, scrollwheel: true, panControl: true, streetViewControl: true, draggable : true, overviewMapControl: true, overviewMapControlOptions: { opened: true, }, mapTypeId: google.maps.MapTypeId.ROADMAP, styles: [ { "featureType": "water", "elementType": "geometry.fill", "stylers": [ { "color": "#d3d3d3" } ] },{ "featureType": "transit", "stylers": [ { "color": "#808080" }, { "visibility": "off" } ] },{ "featureType": "road.highway", "elementType": "geometry.stroke", "stylers": [ { "visibility": "on" }, { "color": "#b3b3b3" } ] },{ "featureType": "road.highway", "elementType": "geometry.fill", "stylers": [ { "color": "#ffffff" } ] },{ "featureType": "road.local", "elementType": "geometry.fill", "stylers": [ { "visibility": "on" }, { "color": "#ffffff" }, { "weight": 1.8 } ] },{ "featureType": "road.local", "elementType": "geometry.stroke", "stylers": [ { "color": "#d7d7d7" } ] },{ "featureType": "poi", "elementType": "geometry.fill", "stylers": [ { "visibility": "on" }, { "color": "#ebebeb" } ] },{ "featureType": "administrative", "elementType": "geometry", "stylers": [ { "color": "#a7a7a7" } ] },{ "featureType": "road.arterial", "elementType": "geometry.fill", "stylers": [ { "color": "#ffffff" } ] },{ "featureType": "road.arterial", "elementType": "geometry.fill", "stylers": [ { "color": "#ffffff" } ] },{ "featureType": "landscape", "elementType": "geometry.fill", "stylers": [ { "visibility": "on" }, { "color": "#efefef" } ] },{ "featureType": "road", "elementType": "labels.text.fill", "stylers": [ { "color": "#696969" } ] },{ "featureType": "administrative", "elementType": "labels.text.fill", "stylers": [ { "visibility": "on" }, { "color": "#737373" } ] },{ "featureType": "poi", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] },{ "featureType": "poi", "elementType": "labels", "stylers": [ { "visibility": "off" } ] },{ "featureType": "road.arterial", "elementType": "geometry.stroke", "stylers": [ { "color": "#d6d6d6" } ] },{ "featureType": "road", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] },{ },{ "featureType": "poi", "elementType": "geometry.fill", "stylers": [ { "color": "#dadada" } ] } ], } var mapElement = document.getElementById('map-canvas'); var map = new google.maps.Map(mapElement, mapOptions); var locations = [ ['Headquarter', '&lt;address&gt;Via Ottavio Assarotti, 10 - Torino &lt;br /&gt; 10122 Italy&lt;/address&gt;', 'Phone: +39 011 549444', 'undefined', 'undefined', 45.0735671, 7.67406040000003, 'https://mapbuildr.com/assets/img/markers/solid-pin-blue.png'],['Offices - Europe', 'Str. del Redentore Alto, 157 Moncalieri TO\"&lt;br /&gt;10024 Italy', 'Phone: +39 011 0603933 &lt;br /&gt; Mobile: +39 335 8291680', '[email protected] &lt;br /&gt; [email protected]', 'undefined', 45.026912, 7.735915, 'https://mapbuildr.com/assets/img/markers/solid-pin-blue.png'],['Russia', 'Alberto Fiocchi&lt;br /&gt;16, Teterinskiy Pereulok &lt;br /&gt;109004 Moscow (Russia)', 'Mobile: +7 985 8546283', '[email protected]', 'undefined', 55.7453888, 37.65318679999996, 'https://mapbuildr.com/assets/img/markers/solid-pin-blue.png'],['China', 'Ines Tammaro&lt;br /&gt;Yangtze river international garden phase II&lt;br /&gt;Shanghai China', 'Phone: +86 158 9648 1992 Mobile: +86 331 2166946', '[email protected]', 'undefined', 31.104447, 121.432655, 'https://mapbuildr.com/assets/img/markers/solid-pin-blue.png'],['USA', 'Jerry Yocum&lt;br /&gt;835, Bunty Station Road,&lt;br /&gt;43015 Delaware, OH – USA', 'Phone: +1 (614) 7361111', '[email protected]', 'undefined', 40.250594, -83.07493899999997, 'https://mapbuildr.com/assets/img/markers/solid-pin-blue.png'],['ASIAN', 'Hubert Fournier&lt;br /&gt;116, Middle Road, ICB Enterprise House,&lt;br /&gt;#08-03/04, 188972 Singapore', 'Phone: (65) 63339833', '[email protected]', 'undefined', 1.2992375, 103.7835042, 'https://mapbuildr.com/assets/img/markers/solid-pin-blue.png'] ]; for (i = 0; i &lt; locations.length; i++) { if (locations[i][1] =='undefined'){ description ='';} else { description = locations[i][1];} if (locations[i][2] =='undefined'){ telephone ='';} else { telephone = locations[i][2];} if (locations[i][3] =='undefined'){ email ='';} else { email = locations[i][3];} if (locations[i][4] =='undefined'){ web ='';} else { web = locations[i][4];} if (locations[i][7] =='undefined'){ markericon ='';} else { markericon = locations[i][7];} marker = new google.maps.Marker({ icon: markericon, position: new google.maps.LatLng(locations[i][5], locations[i][6]), map: map, title: locations[i][0], desc: description, tel: telephone, email: email, web: web }); link = ''; bindInfoWindow(marker, map, locations[i][0], description, telephone, email, web, link); } function bindInfoWindow(marker, map, title, desc, telephone, email, web, link) { var infoWindowVisible = (function () { var currentlyVisible = false; return function (visible) { if (visible !== undefined) { currentlyVisible = visible; } return currentlyVisible; }; }()); iw = new google.maps.InfoWindow(); google.maps.event.addListener(marker, 'click', function() { if (infoWindowVisible()) { iw.close(); infoWindowVisible(false); } else { var html= "&lt;div style='color:#000;background-color:#fff;padding:5px;width:150px;'&gt;&lt;h4&gt;"+title+"&lt;/h4&gt;&lt;p&gt;"+desc+"&lt;p&gt;&lt;p&gt;"+telephone+"&lt;p&gt;&lt;a href='mailto:"+email+"' &gt;"+email+"&lt;a&gt;&lt;/div&gt;"; iw = new google.maps.InfoWindow({content:html}); iw.open(map,marker); infoWindowVisible(true); } }); google.maps.event.addListener(iw, 'closeclick', function () { infoWindowVisible(false); }); } } &lt;/script&gt; &lt;style&gt; #map-canvas { height:400px; width:1024px; } .gm-style-iw * { display: block; width: 100%; } .gm-style-iw h4, .gm-style-iw p { margin: 0; padding: 0; } .gm-style-iw a { color: #4272db; } &lt;/style&gt; &lt;div id="map-canvas"/&gt; </code></pre>
38,160,097
5
0
null
2016-07-02 12:10:44.723 UTC
1
2020-10-10 21:51:03.787 UTC
null
null
null
null
6,541,325
null
1
10
javascript|google-maps|google-maps-api-3
86,101
<p>Quick F12 to developer console and reload gives:</p> <p>MissingKeyMapError and points to <a href="https://developers.google.com/maps/documentation/javascript/error-messages" rel="noreferrer">https://developers.google.com/maps/documentation/javascript/error-messages</a> for reference.</p>