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,064,209
Getting "[archiver] unsupported version (1.13) in file header" when running pg_restore
<p>I just upgraded to postgres 10.2 on mac os which matches 10.2 on heroku. I'm trying to download a copy of the database and restore it locally. Before the upgrade the restore would work fine.</p> <p>I run</p> <pre><code>pg_restore --verbose --clean --no-acl --no-owner -h localhost -d database_name backup.dump </code></pre> <p>but I am getting this error:</p> <blockquote> <p>pg_restore: [archiver] unsupported version (1.13) in file header</p> </blockquote> <p>The database appears to be working OK. It's a rails app and I upgraded the pg gems. I can run <code>rake db:create</code> and <code>db:migrate</code> just fine. </p>
49,064,959
14
0
null
2018-03-02 07:03:01.977 UTC
19
2021-01-14 15:25:55.7 UTC
2018-03-12 16:01:30 UTC
null
1,685,157
null
177,489
null
1
172
postgresql|heroku|pg-restore
106,274
<p>You need to upgrade your local postgres to get the last security patch from the 2018-03-01, like <code>Heroku</code> did the 1st march. You need one of the last releases <code>10.3</code>, <code>9.6.8</code>, <code>9.5.12</code>, <code>9.4.17</code>, and <code>9.3.22</code>. </p> <p>The security patch can be found here <a href="https://www.postgresql.org/about/news/1834/" rel="noreferrer">https://www.postgresql.org/about/news/1834/</a>. </p> <p>It seems the patch modified pg_dump, that's probably why we can't use pg_restore anymore without that patch for the dump of Heroku (with the patch applied).</p>
19,500,332
Spring Security and JSON Authentication
<p>I've an application in spring/spring-mvc that totally uses JSON communications. Now I need to authenticate my application with spring security 3 (that uses LdapAuthenticationProvider) via JSON.</p> <p>The default spring seurity submit form requires a POST like this:</p> <pre><code>POST /myapp/j_spring_security_check HTTP/1.1 Accept-Encoding: gzip,deflate Content-Type: application/x-www-form-urlencoded Content-Length: 32 Host: 127.0.0.1:8080 Connection: Keep-Alive User-Agent: Apache-HttpClient/4.1.1 (java 1.5) j_username=myUsername&amp;j_password=myPass </code></pre> <p>But I want to pass a JSON object like this:</p> <pre><code>{"j_username":"myUsername","j_password":"myPass"} </code></pre> <p>I read many post like <a href="https://stackoverflow.com/questions/3444864/ajax-login-with-spring-webmvc-and-spring-security">this</a>, <a href="http://gal-levinsky.blogspot.co.il/2011/08/spring-security-3-ajax-login.html" rel="noreferrer">this other</a> or <a href="http://raibledesigns.com/rd/entry/implementing_ajax_authentication_using_jquery" rel="noreferrer">this one</a> without luck, in all ajax cases is done a POST like above.</p> <p>Any Ideas?</p>
19,501,060
8
0
null
2013-10-21 16:51:37.853 UTC
22
2018-10-26 10:17:53.557 UTC
2017-05-23 12:10:26.62 UTC
null
-1
null
2,186,777
null
1
37
json|spring|spring-mvc|spring-security
58,915
<p>You can write your own security filter that will parse your JSON.</p> <p><a href="http://docs.spring.io/spring-security/site/docs/3.0.x/reference/core-web-filters.html" rel="noreferrer">http://docs.spring.io/spring-security/site/docs/3.0.x/reference/core-web-filters.html</a></p> <p>You can use the BasicAuthenticationFilter as a reference:</p> <p><a href="http://docs.spring.io/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/authentication/www/BasicAuthenticationFilter.html" rel="noreferrer">http://docs.spring.io/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/authentication/www/BasicAuthenticationFilter.html</a></p>
48,872,042
How do I get a pod's (milli)core CPU usage with Prometheus in Kubernetes?
<p>I run a <code>v1.9.2</code> custom setup of Kubernetes and scrape various metrics with Prometheus <code>v2.1.0</code>. Among others, I scrape the <code>kubelet</code> and <code>cAdvisor</code> metrics.</p> <p>I want to answer the question: "<em>How much of the CPU resources defined by <code>requests</code> and <code>limits</code> in my deployment are actually used by a pod (and its containers) in terms of (milli)cores?</em>"</p> <p>There are a lot of scraped metrics available, but nothing like that. Maybe it could be calculated by the CPU usage time in seconds, but I don't know how.</p> <p>I was considering it's not possible - until a friend told me she runs Heapster in her cluster which has a graph in the built-in Grafana that tells <em>exactly</em> that: It shows the indivual CPU usage of a pod and its containers in (milli)cores.</p> <p>Since Heapster also uses <code>kubelet</code> and <code>cAdvisor</code> metrics, I wonder: how can I calculate the same? The metric in InfluxDB is named <code>cpu/usage_rate</code> but even with Heapster's code, I couldn't figure out how they calculate it.</p> <p>Any help is appreciated, thanks!</p>
48,872,951
2
0
null
2018-02-19 18:21:37.017 UTC
13
2022-03-30 09:00:25.35 UTC
null
null
null
null
1,853,162
null
1
17
kubernetes|prometheus
13,481
<p>We're using the <code>container_cpu_usage_seconds_total</code> metric to calculate Pod CPU usage. This metrics contains the total amount of CPU seconds consumed <em>by container by core</em> (this is important, as a Pod may consist of multiple containers, each of which can be scheduled across multiple cores; however, the metric has a <code>pod_name</code> annotation that we can use for aggregation). Of special interest is the <strong>change rate</strong> of that metric (which can be calculated with <a href="https://prometheus.io/docs/prometheus/latest/querying/functions/#rate()" rel="noreferrer">PromQL's <code>rate()</code> function</a>). If it increases by 1 within one second, the Pod consumes 1 CPU core (or 1000 milli-cores) in that second.</p> <p>The following PromQL query does just that: Compute the CPU usage of all Pods (using the <a href="https://prometheus.io/docs/prometheus/latest/querying/operators/#aggregation-operators" rel="noreferrer"><code>sum(...) by (pod_name)</code></a> operation) over a five minute average:</p> <pre><code>sum(rate(container_cpu_usage_seconds_total[5m])) by (pod_name) </code></pre>
42,229,149
How to update multiple items in a DynamoDB table at once
<p>I'm using DynamoDB and I need to update a specific attribute on multiple records. Writing my requirement in pseudo-language I would like to do an update that says "update table <em>persons</em> set relationshipStatus = 'married' where personKey IN (key1, key2, key3, ...)" (assuming that personKey is the KEY in my DynamoDB table).</p> <p>In other words, I want to do an update with an IN-clause, or I suppose one could call it a batch update. I have found <a href="https://stackoverflow.com/questions/40478904/dynamodb-batch-update">this</a> link that asks explicitly if an operation like a batch update exists and the answer there is that it does not. It does not mention IN-clauses, however. The <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html" rel="noreferrer">documentation</a> shows that IN-clauses are supported in ConditionalExpressions (100 values can be supplied at a time). However, I am not sure if such an IN-clause is suitable for my situation because I still need to supply a mandatory KEY attribute (which expects a single value it seems - I might be wrong) and I am worried that it will do a full table scan for each update.</p> <p>So my question is: how do I achieve an update on multiple DynamoDB records at the same time? At the moment it almost looks like I will have to call an update statement for each Key one-by-one and that just feels really wrong...</p>
42,229,801
5
0
null
2017-02-14 14:49:23.177 UTC
9
2022-05-06 06:48:34.287 UTC
2017-09-22 18:01:22.247 UTC
null
-1
null
1,210,718
null
1
42
amazon-web-services|amazon-dynamodb|nosql
69,679
<p>As you noted, DynamoDB does not support a batch update operation. You would need to query for, and obtain the keys for all the records you want to update. Then loop through that list, updating each item one at a time.</p>
37,136,679
How to convert a list of enity object to page object in Spring MVC (JPA)?
<p>I have a <code>List</code> of entities. How do I convert it to <code>Page</code> Object using Spring MVC 4 and Spring Data JPA?</p>
37,137,170
6
0
null
2016-05-10 11:04:03.153 UTC
13
2021-12-10 17:50:10.223 UTC
2021-06-16 17:59:20.17 UTC
null
5,968,171
null
5,968,171
null
1
67
java|spring-mvc|pagination|spring-data
101,963
<p>There is a <a href="http://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/domain/PageImpl.html" rel="noreferrer"><code>Page</code> implementation</a> for that:</p> <pre><code>final Page&lt;Something&gt; page = new PageImpl&lt;&gt;(theListOfSomething); </code></pre>
20,551,566
Display current date and time without punctuation
<p>For example, I want to display current date and time as the following format:</p> <pre><code>yyyymmddhhmmss </code></pre> <p>How do I do that? It seems like most date format comes with <code>-</code>, <code>/</code>, <code>:</code>, etc.</p>
20,551,593
5
0
null
2013-12-12 18:39:57.723 UTC
22
2018-08-11 17:06:19.193 UTC
2018-08-11 17:06:19.193 UTC
null
6,862,601
null
1,454,510
null
1
131
bash|shell|date
124,460
<p>Here you go:</p> <pre><code>date +%Y%m%d%H%M%S </code></pre> <p>As <code>man date</code> says near the top, you can use the <code>date</code> command like this:</p> <blockquote> <pre><code>date [OPTION]... [+FORMAT] </code></pre> </blockquote> <p>That is, you can give it a format parameter, starting with a <code>+</code>. You can probably guess the meaning of the formatting symbols I used:</p> <ul> <li><code>%Y</code> is for year</li> <li><code>%m</code> is for month</li> <li><code>%d</code> is for day</li> <li>... and so on</li> </ul> <p>You can find this, and other formatting symbols in <code>man date</code>.</p>
19,125,091
Pandas Merge - How to avoid duplicating columns
<p>I am attempting a merge between two data frames. Each data frame has two index levels (date, cusip). In the columns, some columns match between the two (currency, adj date) for example.</p> <p>What is the best way to merge these by index, but to not take two copies of currency and adj date.</p> <p>Each data frame is 90 columns, so I am trying to avoid writing everything out by hand.</p> <pre><code>df: currency adj_date data_col1 ... date cusip 2012-01-01 XSDP USD 2012-01-03 0.45 ... df2: currency adj_date data_col2 ... date cusip 2012-01-01 XSDP USD 2012-01-03 0.45 ... </code></pre> <p>If I do:</p> <pre><code>dfNew = merge(df, df2, left_index=True, right_index=True, how='outer') </code></pre> <p>I get </p> <pre><code>dfNew: currency_x adj_date_x data_col2 ... currency_y adj_date_y date cusip 2012-01-01 XSDP USD 2012-01-03 0.45 USD 2012-01-03 </code></pre> <p>Thank you! ...</p>
19,125,531
10
0
null
2013-10-01 20:16:26.607 UTC
55
2022-06-10 11:58:51.027 UTC
null
null
null
null
1,911,092
null
1
145
python|pandas
218,433
<p>You can work out the columns that are only in one DataFrame and use this to select a subset of columns in the merge.</p> <pre><code>cols_to_use = df2.columns.difference(df.columns) </code></pre> <p>Then perform the merge (note this is an index object but it has a handy <code>tolist()</code> method).</p> <pre><code>dfNew = merge(df, df2[cols_to_use], left_index=True, right_index=True, how='outer') </code></pre> <p>This will avoid any columns clashing in the merge.</p>
18,909,649
What is the RWS Monad and when is it used
<p>I ran across the RWS Monad and its MonadTransformer while looking up something in the mtl library. There is no real documentation there, and I was wondering what this is and where it gets used.</p> <p>I've gotten as far as finding that RWS is an acronym fro Reader, Writer, State and that is is a stack of those three monad transformers. What I cannot figure out is why this is better then State by itself.</p>
18,911,314
2
0
null
2013-09-20 05:45:56.063 UTC
7
2013-09-20 07:36:22.763 UTC
null
null
null
null
163,177
null
1
29
haskell|monad-transformers
4,427
<p>The most practical reason for this is for testability and for more precise type signatures.</p> <p>The key strength of haskell is how well you can specify what a function does through the type system. Compare the c#/java type:</p> <pre><code>public int CSharpFunction(int param) { ... </code></pre> <p>with a haskell one:</p> <pre><code>someFunction :: Int -&gt; Int </code></pre> <p>The haskell one not only tells us the types needed for parameters and the return type, but also what the function may affect. For example, it can't do any IO, nor can it read or change any global state, or access any static configuration data. Neither may be true for the c# function, but we cannot tell.</p> <p>This is a great help with testing. We know that the only things we need to test with the haskell <code>someFunction</code> is if it gets the expected outputs for some sample inputs. There isn't any possible setup required, and the function will never give a different result for the same input. This makes testing pretty simple with pure functions.</p> <hr> <p>However, often a function cannot be pure. For example, it may need to access some global information just for reading. We could just add another parameter to the function:</p> <pre><code>readerFunc :: GlobalConfig -&gt; Int -&gt; Int </code></pre> <p>But it is often easier to use a monad, since they are easier to compose:</p> <pre><code>readerFunc2 :: Int -&gt; Reader GlobalConfig Int </code></pre> <p>Testing this is almost as easy as testing a pure function. We just need to test various permutations of the input Int value, and the GlobalConfig reader configuration value.</p> <p>A function may need to write out values (eg for logging). This can also be done with a monad:</p> <pre><code>writerFunc :: Int -&gt; Writer String Int </code></pre> <p>Again testing this is almost as easy as for a pure function. We just test if for a given <code>Int</code> input, the appropriate <code>Int</code> is returned, as well as the right final writer <code>String</code>.</p> <p>Another function may need to read and change state:</p> <pre><code>stateFunc :: Int -&gt; State GlobalState Int </code></pre> <p>This is harder to test though. Not only do we have to check the output using various input Ints and initial GlobalStates, but we also need to test if the final GlobalState is the correct value. </p> <hr> <p>Now consider a function which:</p> <ul> <li>Needs to read from a ProgramConfig data type</li> <li>Write values to a string for logging</li> <li>Use and modify a <code>ProgramState</code> value.</li> </ul> <p>We could do something like this:</p> <pre><code>data ProgramData = ProgramData { pState :: ProgramState, pConfig :: ProgramConfig, pLogs :: String } complexFunction :: Int -&gt; State ProgramData Int </code></pre> <p>However, that type isn't very accurate. It implies that the ProgramConfig may be changed, which it won't. It also implies that the function may use the pLogs value, which it won't. Also, testing it is more complex, as theoretically, the function could accidently change the program config, or use the current pLogs value in its computations.</p> <p>This can be greatly improved upon with this:</p> <pre><code>betterFunction :: Int -&gt; RWS ProgramConfig String ProgramState Int </code></pre> <p>This type is very accurate. We know that the ProgramConfig is only ever read from. We know the <code>String</code> is only ever changed. The only part that requires both reading and writing is the <code>ProgramState</code>, as expected. This is easier to test, as we only need to test different combinations of ProgramConfig, ProgramState and <code>Int</code> for input, and check the output <code>Int</code>, <code>String</code> and <code>ProgramState</code> for output. We know we cannot accidently change the program config, or use the current program log value in our computations.</p> <hr> <p>The haskell type system is there to help us, we should give it as much information as we can so it can catch errors before we do.</p> <p>(Note that every haskell type in this answer could be the equivalent to the c# type at the top, depending on how the c# function is actually implemented).</p>
49,057,054
Adding an Alias to a Microsoft O365 Group
<p>Wanted to add an answer to what I learned after researching and succeeding with this issue.</p> <p>I have a Microsoft O365 account where I run my business. I am using Microsoft Teams so my executive team can see information and emails specific to that function. For instance, Human Resources. That team is setup to use [email protected] as its email Office 365 Group. I want to add [email protected] as an alias to the group. But the O365 Admin panel or Exchange Admin Center (EAC) do not have that function available. How do you add an Alias to a Microsoft O365 Group?</p>
49,057,055
5
2
null
2018-03-01 19:10:28.937 UTC
8
2019-10-22 23:15:41.7 UTC
null
null
null
null
1,544,175
null
1
8
powershell|office365|microsoft-teams
34,649
<p>There is a link that describes how to use PowerShell to add an alias:</p> <p><a href="https://answers.microsoft.com/en-us/msoffice/forum/msoffice_o365admin-mso_password-mso_o365b/add-additional-smtp-aliases-to-office-365-groups/b017e4b9-a0e2-4295-a40e-9ca2ec359965?auth=1" rel="noreferrer">Add Additional SMTP Aliases to Office 365 Groups</a></p> <p><strong>Concise Instructions</strong></p> <p>Open PowerShell.</p> <p>Allow Remote, Signed scripts so you can import Microsoft O365 Exchange commands. We will set this back to default when done:</p> <pre><code>Set-ExecutionPolicy RemoteSigned </code></pre> <p>Enter your credentials so you can manage the O365 environment you are working on. It will prompt you for your username and your password:</p> <pre><code>$UserCredential = Get-Credential </code></pre> <p>Create a new PowerShell session to import the Microsoft O365 Exchange commands:</p> <pre><code>$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection </code></pre> <p>Import the session. You should see the standard PowerShell progress bar as the commands are imported:</p> <pre><code>Import-PSSession $Session </code></pre> <p>Now you are ready to issue your commands. First, make sure you can read the properties of the Exchange Group:</p> <pre><code>Get-UnifiedGroup -Identity [email protected] | FL EmailAddresses </code></pre> <p>It should output the aliases assigned to the Outlook Group.</p> <p>To add the alias, enter this command. I will use my example in the question above to show what it looks like:</p> <pre><code>Set-UnifiedGroup -Identity [email protected] -EmailAddresses @{Add="[email protected]"} </code></pre> <p>You can then run the <code>Get-UnifiedGroup</code> command and see the alias now listed in the email addresses.</p> <p>Return to the default execution policy:</p> <pre><code>Set-ExecutionPolicy Default </code></pre> <p><strong>Next Steps</strong></p> <p>At this point the group has an alias. You can email the alias internally to your O365 account. For instance, [email protected] can email [email protected] and it will work correctly. It will be received in your O365 Human Resources group.</p> <p>However, if you attempt to send email to the alias from external, you will get a 5.4.1 access denied error. You will get this even if you are able to email [email protected]. (If you can't email the primary alias externally, you have another problem where the group is not set to receive external email, that can be set in the EAC.)</p> <p>The problem where the alias cannot receive external email has to do with <a href="https://technet.microsoft.com/en-us/library/dn600322(v=exchg.150).aspx" rel="noreferrer">Directory Based Edge Blocking (DBEB)</a>. Essentially, before O365 performs any of its protection actions (anti-malware, anti-virus, SPAM, etc.) it performs a simple lookup into your Active Directory. It looks to see "Hey, does this user even exist here?"</p> <p>For instance, if you are sending email to [email protected], DBEB looks up the directory and say, OK, that user exists, send it on. It does the same for [email protected]. However, the lookup fails for additional aliases assigned to O365 Groups. There is a workaround.</p> <p><strong>Workaround</strong></p> <p>The workaround is disabling DBEB for the contoso.com domain. This <strong>does not</strong> disable the additional layers of protection of email hygiene (anti's, spam, etc.). To do so, you need to go into the EAC of your O365 account and change the <a href="https://technet.microsoft.com/en-us/library/jj945194(v=exchg.150).aspx" rel="noreferrer">Accepted Domains</a> from Authoritative to Internal relay.</p> <p>If you have natively started in O365, this is probably set to Authoritative. If you have a hybrid (O365 and Onsite), or did a migration from Onsite to O365 it is most likely already set to Internal relay (Unless post-migration you changed it to Authoritative). This is why for some people, just adding the alias works for them. DBEB is already disabled. Again, this only disables the first check of a valid user or not and the remainder of the hygiene stack is still in place.</p> <p>After this change, your O365 Groups should now receive external email to their additional aliases.</p> <p><strong>Better Ways?</strong></p> <p>Yes, there should be better ways to add aliases to O365 Groups, like going to the group, selecting aliases, and adding them. That way we aren't in the shell and EAC making things work like they should. Microsoft, make it so!</p> <p>Another way may be somehow to use <code>New-EOPMailUser</code> to create an entry in the Directory for the alias. When I tried to create a new Contact in the EAC, it stated that the email address was already in use. So, I got it to work and haven't looked at other options. I am assuming Microsoft will get aliases added in a more admin friendly way (PLEASE?!).</p> <p>Keep Calm and Cloud On!</p>
27,484,126
Adjust icon size of Floating action button (fab)
<p><img src="https://i.stack.imgur.com/N4Jzt.png" alt="Floating button"> The new floating action button should be <strong>56dp x 56dp</strong> and the icon inside it should be <strong>24dp x 24dp</strong>. So the space between icon and button should be <strong>16dp</strong>.</p> <pre><code>&lt;ImageButton android:id="@+id/fab_add" android:layout_width="56dp" android:layout_height="56dp" android:layout_gravity="bottom|right" android:layout_marginBottom="16dp" android:layout_marginRight="16dp" android:background="@drawable/ripple_oval" android:elevation="8dp" android:src="@drawable/ic_add_black_48dp" /&gt; </code></pre> <p>ripple_oval.xml </p> <pre><code>&lt;ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="?android:colorControlHighlight"&gt; &lt;item&gt; &lt;shape android:shape="oval"&gt; &lt;solid android:color="?android:colorAccent" /&gt; &lt;/shape&gt; &lt;/item&gt; &lt;/ripple&gt; </code></pre> <p>And this is the result I get: <br> <img src="https://i.stack.imgur.com/8BVKM.png" alt="Floating button result"> <br> I used the icon from <em>\material-design-icons-1.0.0\content\drawable-hdpi\ic_add_black_48dp.png</em> <br> <a href="https://github.com/google/material-design-icons/releases/tag/1.0.1">https://github.com/google/material-design-icons/releases/tag/1.0.1</a></p> <p>How to make the <strong>size of the icon</strong> inside the button be <strong>exactly</strong> as described in guidelines ?</p> <p><a href="http://www.google.com/design/spec/components/buttons.html#buttons-floating-action-button">http://www.google.com/design/spec/components/buttons.html#buttons-floating-action-button</a></p>
27,484,368
14
1
null
2014-12-15 12:28:27.427 UTC
33
2021-09-30 21:33:42.543 UTC
2020-08-03 12:03:16.593 UTC
null
7,585,388
null
1,502,079
null
1
210
android|material-design|floating-action-button|material-components-android|android-icons
229,281
<p>As your content is 24dp x 24dp you should use <a href="https://github.com/google/material-design-icons/blob/master/content/drawable-hdpi/ic_add_black_24dp.png">24dp icon</a>. And then set <code>android:scaleType="center"</code> in your ImageButton to avoid auto resize.</p>
21,861,366
.NET StringBuilder preappend a line
<p>I know that the <code>System.Text.StringBuilder</code> in .NET has an <code>AppendLine()</code> method, however, I need to pre-append a line to the beginning of a <code>StringBuilder</code>. I know that you can use <code>Insert()</code> to append a string, but I can't seem to do that with a line, is there a next line character I can use? I am using VB.NET, so answers in that are preferable, but answers in C# are ok as well.</p>
21,861,395
2
1
null
2014-02-18 17:41:07.02 UTC
2
2014-02-18 18:06:51.297 UTC
2014-02-18 17:44:50.81 UTC
null
120,753
null
1,066,445
null
1
28
c#|.net|vb.net|stringbuilder
28,200
<blockquote> <p>is there a next line character I can use?</p> </blockquote> <p>You can use <a href="http://msdn.microsoft.com/en-us/library/system.environment.newline%28v=vs.110%29.aspx"><code>Environment.NewLine</code></a></p> <blockquote> <p>Gets the newline string defined for this environment.</p> </blockquote> <p>For example:</p> <pre><code>StringBuilder sb = new StringBuilder(); sb.AppendLine("bla bla bla.."); sb.Insert(0, Environment.NewLine); </code></pre> <p>Or even better you can write a simple extension method for that:</p> <pre><code>public static class MyExtensions { public static StringBuilder Prepend(this StringBuilder sb, string content) { return sb.Insert(0, content); } } </code></pre> <p>Then you can use it like this:</p> <pre><code>StringBuilder sb = new StringBuilder(); sb.AppendLine("bla bla bla.."); sb.Prepend(Environment.NewLine); </code></pre>
21,722,375
Object of class mysqli_result could not be converted to string
<p>I am getting the error:</p> <blockquote> <p>Object of class mysqli_result could not be converted to string</p> </blockquote> <p>This is my code:</p> <pre><code>$result = mysqli_query($con, &quot;SELECT classtype FROM learn_users WHERE username='abcde'&quot;); echo &quot;my result &lt;a href='data/$result.php'&gt;My account&lt;/a&gt;&quot;; </code></pre>
21,722,416
5
2
null
2014-02-12 08:26:28.763 UTC
12
2022-07-12 10:55:45.85 UTC
2021-04-05 15:24:23.75 UTC
null
2,756,409
null
3,206,635
null
1
31
php|mysqli
247,591
<p><strong>The <code>mysqli_query()</code> method returns an object resource to your <code>$result</code> variable, not a string.</strong></p> <p>You need to loop it up and then access the records. You just can't directly use it as your <code>$result</code> variable.</p> <pre><code>while ($row = $result-&gt;fetch_assoc()) { echo $row['classtype'].&quot;&lt;br&gt;&quot;; } </code></pre>
42,508,640
Facebook-passport with JWT
<p>I've been using <strong>Passport</strong> on my server for user authentication. When a user is signing in locally (using a username and password), the server sends them a <strong>JWT</strong> which is stored in localstorage, and is sent back to server for every api call that requires user authentication.</p> <p>Now I want to support <strong>Facebook and Google login</strong> as well. Since I began with Passport I thought it would be best to continue with Passport strategies, using <strong>passport-facebook</strong> and <strong>passport-google-oauth</strong>.</p> <p>I'll refer to Facebook, but both strategies behave the same. They both require redirection to a server route (<strong>'/auth/facebook'</strong> and <strong>'/auth/facebook/callback'</strong> for that matter). The process is successful to the point of saving users including their facebook\google ids and tokens on the DB.</p> <p>When the user is created on the server, a JWT is created (without any reliance on the token received from facebook\google). </p> <pre><code> ... // Passport facebook startegy var newUser = new User(); newUser.facebook = {}; newUser.facebook.id = profile.id; newUser.facebook.token = token; // token received from facebook newUser.facebook.name = profile.displayName; newUser.save(function(err) { if (err) throw err; // if successful, return the new user newUser.jwtoken = newUser.generateJwt(); // JWT CREATION! return done(null, newUser); }); </code></pre> <p>The problem is that after its creation, <strong>I don't find a proper way to send the JWT to the client</strong>, since I should also redirect to my app.</p> <pre><code>app.get('/auth/facebook/callback', passport.authenticate('facebook', { session: false, successRedirect : '/', failureRedirect : '/' }), (req, res) =&gt; { var token = req.user.jwtoken; res.json({token: token}); }); </code></pre> <p>The code above <strong>redirects me to my app main page, but I don't get the token</strong>. If I remove the successRedirect, <strong>I do get the token, but I'm not redirected to my app</strong>.</p> <p>Any solution for that? Is my approach wrong? Any suggestions will do. </p>
48,851,674
3
2
null
2017-02-28 12:20:49.477 UTC
10
2021-01-22 17:34:59.527 UTC
null
null
null
null
7,324,798
null
1
32
node.js|mongodb|passport.js|passport-facebook|express-jwt
9,759
<p>The best solution I found for that problem would be to redirect to the expected page with a cookie which holds the JWT.</p> <p>Using <code>res.json</code> would only send a json response and would not redirect. That's why the other suggested answer here would not solve the problem I encountered.</p> <p>So my solution would be:</p> <pre><code>app.get('/auth/facebook/callback', passport.authenticate('facebook', { session: false, successRedirect : '/', failureRedirect : '/' }), (req, res) =&gt; { var token = req.user.jwtoken; res.cookie('auth', token); // Choose whatever name you'd like for that cookie, res.redirect('http://localhost:3000'); // OR whatever page you want to redirect to with that cookie }); </code></pre> <p>After redirection, you can read the cookie safely and use that JWT as expected. (you can actually read the cookie on every page load, to check if a user is logged in)</p> <p>As I mentioned before, it is possible to redirect with the JWT as a query param, but it's very unsafe. Using a cookie is safer, and there are still security solutions you can use to make it even safer, unlike a query param which is plainly unsecure.</p>
33,058,590
Pandas Dataframe: Replacing NaN with row average
<p>I am trying to learn pandas but I have been puzzled with the following. I want to replace NaNs in a DataFrame with the row average. Hence something like <code>df.fillna(df.mean(axis=1))</code> should work but for some reason it fails for me. Am I missing anything, is there something wrong with what I'm doing? Is it because its not implemented? see <a href="https://stackoverflow.com/questions/29478641/how-to-replace-nan-with-sum-of-the-row-in-pandas-datatframe">link here</a></p> <pre><code>import pandas as pd import numpy as np ​ pd.__version__ Out[44]: '0.15.2' In [45]: df = pd.DataFrame() df['c1'] = [1, 2, 3] df['c2'] = [4, 5, 6] df['c3'] = [7, np.nan, 9] df Out[45]: c1 c2 c3 0 1 4 7 1 2 5 NaN 2 3 6 9 In [46]: df.fillna(df.mean(axis=1)) Out[46]: c1 c2 c3 0 1 4 7 1 2 5 NaN 2 3 6 9 </code></pre> <p>However something like this looks to work fine</p> <pre><code>df.fillna(df.mean(axis=0)) Out[47]: c1 c2 c3 0 1 4 7 1 2 5 8 2 3 6 9 </code></pre>
33,058,777
6
1
null
2015-10-10 20:21:04.6 UTC
7
2022-04-16 18:26:05.437 UTC
2022-03-08 11:04:17.52 UTC
user7864386
null
null
5,431,734
null
1
29
python|pandas|dataframe|missing-data
24,244
<p>As commented the axis argument to fillna is <a href="https://github.com/pydata/pandas/issues/4514" rel="nofollow noreferrer">NotImplemented</a>.</p> <pre><code>df.fillna(df.mean(axis=1), axis=1) </code></pre> <p><em>Note: this would be critical here as you don't want to fill in your nth columns with the nth row average.</em></p> <p>For now you'll need to iterate through:</p> <pre><code>m = df.mean(axis=1) for i, col in enumerate(df): # using i allows for duplicate columns # inplace *may* not always work here, so IMO the next line is preferred # df.iloc[:, i].fillna(m, inplace=True) df.iloc[:, i] = df.iloc[:, i].fillna(m) print(df) c1 c2 c3 0 1 4 7.0 1 2 5 3.5 2 3 6 9.0 </code></pre> <p>An alternative is to fillna the transpose and then transpose, which may be more efficient...</p> <pre><code>df.T.fillna(df.mean(axis=1)).T </code></pre>
33,290,564
Callback function syntax in Swift
<p>I am attempting pass a function to another function and then have the passed function executed passing to it a variable.</p> <p>Here is my code:</p> <pre><code>func showStandardPrompt(prompt:String,view: UIViewController,numberInput: Bool, callback: (()-&gt;(String))?) { let alert = UIAlertController(title: "Input Data", message: prompt, preferredStyle: .Alert) alert.addTextFieldWithConfigurationHandler { (textField) in if numberInput { textField.keyboardType = .NumberPad } } let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in let field = alert.textFields![0] as UITextField callback?(field.text!) } alert.addAction(OKAction) let CancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil) alert.addAction(CancelAction) view.presentViewController(alert,animated: true, completion: nil) } </code></pre> <p>The error I get is in</p> <pre><code>callback?(field.text!) </code></pre> <p>The error is "Cannot convert value type of 'String' to expected argument type '()'. I know it's a matter of syntax - just don't know what it should be.</p>
33,290,780
5
1
null
2015-10-22 20:54:05.887 UTC
13
2020-06-11 07:51:50.947 UTC
2015-10-23 00:00:27.807 UTC
null
77,567
null
2,630,240
null
1
45
ios|swift|function|callback
101,829
<p>Rob's answer is correct, though I'd like to share an example of a simple working callback / completion handler, you can download an example project below and experiment with the <code>getBoolValue</code>'s input.</p> <h2>Swift 5:</h2> <pre><code>func getBoolValue(number : Int, completion: (Bool)-&gt;()) { if number &gt; 5 { completion(true) } else { completion(false) } } getBoolValue(number: 2) { (result) -&gt; () in // do stuff with the result print(result) } </code></pre> <p><strong>Important to understand:</strong></p> <pre><code>(String)-&gt;() // takes a String returns void ()-&gt;(String) // takes void returns a String </code></pre>
33,141,091
Is it good to replace broadcast receiver with Greenrobot Eventbus for triggering event based functions and data transfer from service to activity?
<p>I have implemented a service, where I handle the state changes(connect, disconnect, onServiceDiscoverd, onCharacteristicChange etc) and receiving data from another device through gatt Server.</p> <p>My question is, Can the events be handled efficiently using <strong>Greenrobot Eventbus</strong> replacing broadcast receiver <strong>between service and Activity</strong>?</p>
36,842,172
3
2
null
2015-10-15 06:10:18.267 UTC
9
2019-03-14 16:18:44.283 UTC
null
null
null
null
2,018,343
null
1
19
android|android-service|bluetooth-lowenergy|android-broadcast|greenrobot-eventbus
8,066
<p>Unlike LocalBroadcastManager, EventBus is more simple to use. You only go via 3 steps:</p> <p>1- Create an event class. A simple Java class that represent the response when the action occur.</p> <p>2- Register the event bus as a subscriber in your Activity onCreate method</p> <pre><code> EventBus.getDefault().register(this); </code></pre> <p>And of course, unregister it in your Activity onDestroy method</p> <pre><code> EventBus.getDefault().unregister(this); </code></pre> <p>3- The subscribing method is created in the same activity that registered for the EventBus. Example in WorkOrderActivity</p> <pre><code> @Subscribe public void onEvent(EventClass event) </code></pre> <p><em>When the event occur, you should call the post method, passing the event object you created before.</em></p> <pre><code> EventBus.getDefault().post(new EventClass (Data)); </code></pre> <p>As kmaini mentioned, you can replace it with LocalBroadcastManager, but you will have to map the data from the intent by yourself. Unlike EventBus which can pass objects. </p> <p>Also, greenrobot, the creators of EventBus Library, answered this question <a href="https://greenrobot.github.io/EventBus/" rel="noreferrer">here</a>:</p> <blockquote> <p>Q: How's EventBus different to Android's BroadcastReceiver/Intent system?</p> <p>A: Unlike Android's BroadcastReceiver/Intent system, EventBus uses standard Java classes as events and offers a more convenient API. EventBus is intended for a lot more uses cases where you wouldn't want to go through the hassle of setting up Intents, preparing Intent extras, implementing broadcast receivers, and extracting Intent extras again. Also, EventBus comes with a much lower overhead.</p> </blockquote>
9,143,561
Git "You have not concluded your merge" and nothing to commit?
<p>Whenever I try to push in Git I get this:</p> <pre><code>You have not concluded your merge (MERGE_HEAD exists). Please, commit your changes before you can merge. </code></pre> <p>Running <code>git status</code> I get:</p> <pre><code># On branch master nothing to commit (working directory clean) </code></pre> <p>Or running <code>git ls-files -u</code> I get nothing.</p> <p>Running <code>git add .</code>and trying again makes no difference.</p> <p>What's up?</p>
9,143,629
3
0
null
2012-02-04 18:59:24.75 UTC
18
2019-05-27 08:54:50.29 UTC
null
null
null
null
283,055
null
1
76
git
91,096
<p>Okay I finally found answer: <code>git commit -m "Test"</code> apparently fixed this. The result was an empty commit with no changes whatsoever. Even Github shows an empty commit, but it works.</p>
29,826,442
mkdir command not found in bash script
<p>I don't know why I get error while running this simple script:</p> <pre><code>#!/bin/bash read -p "Please enter directory name: " DIR read -p "Please enter the path: " PATH mkdir -p "$PATH/$DIR" </code></pre> <pre><code>line 7: mkdir: command not found </code></pre>
29,826,572
2
2
null
2015-04-23 14:27:08.22 UTC
2
2015-04-23 15:32:40.443 UTC
2015-04-23 14:29:06.96 UTC
null
418,066
null
2,515,498
null
1
25
bash|mkdir
46,055
<p>Don't use the variable <code>PATH</code>. This variable contains a list of directories to search for executable programs. Since you're replacing it, the script can no longer find the <code>mkdir</code> program.</p> <p>In general, avoid using variables that are all uppercase, these are often used as parameters for the shell or other programs.</p>
31,202,996
Assigning multiple styles on an HTML element
<p>I'm just starting out with HTML and I'm having a trouble assigning multiple styles to a text. I'd like to create a title with two properties:</p> <ol> <li>Centered</li> <li>Font: Tahoma</li> </ol> <p>I have tried this one:</p> <pre><code>&lt;h2 style="text-align:center";"font-family:tahoma"&gt;TITLE&lt;/h2&gt; </code></pre> <p>but it doesn't work...</p> <p>What am I doing wrong?</p>
31,203,184
4
1
null
2015-07-03 09:14:51.373 UTC
13
2022-03-04 02:54:18.727 UTC
2021-03-29 13:18:06.127 UTC
null
2,756,409
null
5,077,133
null
1
49
html|css
230,539
<p>In HTML the style attribute has the following syntax:</p> <pre><code>style=&quot;property1:value1;property2:value2&quot; </code></pre> <p>so in your case:</p> <pre><code>&lt;h2 style=&quot;text-align:center;font-family:tahoma&quot;&gt;TITLE&lt;/h2&gt; </code></pre> <p>Hope this helps.</p>
30,972,578
Route parameter with slash "/" in URL
<p>I know you can apply a wildcard in the route attribute to allow <code>/</code> such as date input for example:</p> <pre><code>[Route("orders/{*orderdate}")] </code></pre> <p>The problem with wildcard is only applicable to the last paramter in URI. How do I solve the issue if want to have the following URI:</p> <pre><code>[Route("orders/{orderdate}/customers")] </code></pre> <p><strong>Update:</strong></p> <p>I know there are few options to solve the issue by refactoring the code so please do not offer a solution something like:</p> <ol> <li>change the route template to <code>[Route("orders/customers/{orderdate}")]</code></li> <li>change the date to a different format (e.g. <code>"dd-mm-yyyy"</code>) </li> </ol>
30,994,100
4
1
null
2015-06-22 05:23:27.7 UTC
6
2022-09-22 15:29:44.19 UTC
2016-04-29 05:41:28.247 UTC
null
41,956
null
4,321,946
null
1
50
c#|url|asp.net-web-api|asp.net-web-api-routing|attributerouting
56,054
<p><em>@bet..</em> I think the <code>genericUriParserOptions</code> is no longer applicable to .net 4.5 or later.. </p> <p>Also as suggested by <em>@JotaBe</em>, you might need to correctly decode the url request. In most case the <code>%2F</code> will be automatically translated to a slash <code>'/'</code>. So if you need to escape it you will need to decode the <code>'%'</code> char in the first place.. so your URL: will look something like: <code>www.domain.com/api/orders/23%252F06%252F2015/customers</code></p> <p>Notice the characters <code>'%252F'</code> will be translated to the actual <code>'%2F'</code></p> <p><strong>EDIT</strong></p> <p>Ok here is the complete solution (Tried it and working for me):</p> <ol> <li><p>Assuming you have an API endpoint like so:</p> <pre><code>[Route("orders/{date}/customers")] public HttpResponseMessage Get(string date) { } </code></pre></li> <li><p>In the <em>web.config</em> you will need to set the <code>requestPathInvalidCharacters</code> to empty which tells the asp.net to allow all request</p> <pre><code>&lt;system.web&gt; &lt;httpRuntime targetFramework="4.5" requestPathInvalidCharacters=""/&gt; &lt;/system.web&gt; &lt;system.webServer&gt; &lt;security&gt; &lt;requestFiltering allowDoubleEscaping="true" /&gt; &lt;/security&gt; &lt;/system.webServer&gt; </code></pre></li> <li><p>When the client sending the request to the API you will need to make sure to escape the <code>'%'</code> like so:</p> <p>www.domain.com/api/orders/23%252F06%252F2015/customers</p></li> <li><p>You then need to decode the request</p> <pre><code>[Route("orders/{date}/customers")] public HttpResponseMessage Get(string date) { DateTime actualDate = DateTime.Parse(System.Net.WebUtility.UrlDecode(date)); // date is 23/06/2015 } </code></pre></li> </ol>
10,657,908
HTML onClick go to another div
<p>I have a button on my webpage which when onClick I want it to show another div. However when I click the button it will flash in the url that it went to the correct div but then it will immediately redirect back to the main div, #home. </p> <p>Code for button:</p> <pre><code>&lt;input type="button" class="flip" value="Redirect To Div" onClick="window.location='#targetDiv'" /&gt; </code></pre> <p>When I click the the button the url will flash:</p> <p>www.XXXXX.com/#targetDiv </p> <p>Then go immediately to www.XXXXX.com/#home</p> <p>Any ideas why it won't display the div?</p> <p>Thanks</p>
10,658,087
2
1
null
2012-05-18 18:28:42.457 UTC
4
2021-08-15 17:22:30.353 UTC
null
null
null
null
1,220,013
null
1
1
javascript|html
56,497
<p>looks like your form has </p> <pre><code> action="" </code></pre> <p>or</p> <pre><code> action="#home" </code></pre> <p>instead of onclick call a function</p> <pre><code> onclick="mylinkfunction()" </code></pre> <p>...</p> <pre><code> &lt;script type-"text/javascript"&gt; function mylinkfunction(e) { window.location.href="#targetDiv"; /* need to stop the form sending of the form UPDATE as comment: This may not be exactly correct syntax for stopping a form , look up preventing form submission */ e.preventDefault(); e.stopPropagation(); } &lt;/script&gt; </code></pre> <p>or if your form is irrelevent set it's action and remove the javascript allogether</p> <pre><code> &lt;form action="#targetDiv" method="get"&gt; &lt;input type="submit" value="go"/&gt; &lt;/form&gt; </code></pre> <p>but then all you would need is actually this .. </p> <pre><code> &lt;a href="#targetDiv"&gt;click me&lt;/a&gt; </code></pre> <p>if by "go to another div" you mean jump and scroll the page to a new location it is actually an anchor you need to go to</p> <pre><code> &lt;a name="targetDiv"/&gt; </code></pre>
10,710,193
How to preserve insertion order in HashMap?
<p>I'm using a <code>HashMap</code>. When I iterate over the map, the data is returned in (often the same) random order. But the data was inserted in a specific order, and I need to preserve the insertion order. How can I do this?</p>
10,710,205
2
1
null
2012-05-22 21:08:23.26 UTC
92
2021-12-15 11:47:21.577 UTC
2019-01-24 16:31:48.95 UTC
null
10,607,772
null
1,055,279
null
1
556
java|hashmap
417,482
<p><a href="http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html" rel="noreferrer"><code>LinkedHashMap</code></a> is precisely what you're looking for.</p> <p>It is exactly like <code>HashMap</code>, except that when you iterate over it, it presents the items in the insertion order.</p>
22,999,487
Update the average of a continuous sequence of numbers in constant time
<p>How can you add and subtract numbers in an average without having to iterate through the entire list?</p> <p>This can be very useful in many situations. For example to continuously calculate the average of the last X values in a stream, adding two averages together, and updating a rating based on a new user vote.</p>
22,999,488
2
1
null
2014-04-10 21:36:25.66 UTC
9
2021-11-08 09:45:40.013 UTC
2019-03-06 15:15:18.753 UTC
null
1,706,816
null
1,706,816
null
1
19
performance|math|iteration|time-complexity|average
13,516
<p>It is indeed possible to manipulate single values in an average in constant time, O(1).</p> <p>The following function adds a number to an average. <code>average</code> is the current average, <code>size</code> is the current number of values in the average, and <code>value</code> is the number to add to the average:</p> <pre><code>double addToAverage(double average, int size, double value) { return (size * average + value) / (size + 1); } </code></pre> <p>Likewise, the following function removes a number from the average:</p> <pre><code>double subtractFromAverage(double average, int size, double value) { // if (size == 1) return 0; // wrong but then adding a value &quot;works&quot; // if (size == 1) return NAN; // mathematically proper // assert(size &gt; 1); // debug-mode check // if(size &lt; 2) throw(...) // always check return (size * average - value) / (size - 1); } </code></pre> <p>You might consider returning <code>0</code> as the average of a set of size 0 just so adding a value back in will give that value as the average. But if you want to consider it a bug to ever reduce your set to size 0, returning <code>NAN</code> will propagate that to future uses, making it more visible. But see <a href="https://stackoverflow.com/questions/39706777/what-is-the-arithmetic-mean-of-an-empty-sequence">What is the arithmetic mean of an empty sequence?</a> - you might want to just noisily report the error on the spot, or throw a C++ exception (not just raise an FP exception) if it's a bug for this to ever happen.</p> <p>If you don't special case it, you'll probably get + or -Inf, from a <code>x / 0.</code> with non-zero <code>x</code>, unless the value you remove is exactly equal to the current average; then you'll get <code>0. / 0.</code> =&gt; NaN.</p> <hr /> <p>You can also combine these functions to easily replace a number. This is very convenient if you are calculating the average of the last X numbers in an array/stream.</p> <pre><code>double replaceInAverage(double average, int size, double oldValue, double newValue) { return (size * average - oldvalue + newValue) / size; } </code></pre> <p>It is also possible to calculate the total average of two averages in constant time:</p> <pre><code>double addAveragesTogether(double averageA, int sizeA, double averageB, int sizeB) { return (sizeA * averageA + sizeB * averageB) / (sizeA + sizeB); } </code></pre>
31,845,421
How to convert dictionary to array
<p>I want to convert my dictionary to an array, by showing each <code>[String : Int]</code> of the dictionary as a string in the array.</p> <p>For example:     </p> <pre><code>var myDict: [String : Int] = ["attack" : 1, "defend" : 5, "block" : 12] </code></pre> <p>     I'm aware of <code>myDict.keys.array</code> and <code>myDict.values.array</code>, but I want them to show up in an array together. Here's what I mean:     </p> <pre><code>var myDictConvertedToArray = ["attack 1", "defend 5", "block 12"] </code></pre> <p>Thanks in advance.</p>
31,845,495
5
1
null
2015-08-06 01:34:02.583 UTC
8
2020-09-15 13:42:09.217 UTC
2015-08-06 02:00:11.62 UTC
null
1,630,618
null
4,143,556
null
1
46
ios|arrays|swift|dictionary
70,870
<p>You can use a for loop to iterate through the dictionary key/value pairs to construct your array:</p> <pre><code>var myDict: [String : Int] = ["attack" : 1, "defend" : 5, "block" : 12] var arr = [String]() for (key, value) in myDict { arr.append("\(key) \(value)") } </code></pre> <p><strong>Note:</strong> Dictionaries are <em>unordered</em>, so the order of your array might not be what you expect.</p> <hr> <p>In <strong>Swift 2</strong> and later, this also can be done with <code>map</code>:</p> <pre><code>let arr = myDict.map { "\($0) \($1)" } </code></pre> <p>This can also be written as:</p> <pre><code>let arr = myDict.map { "\($0.key) \($0.value)" } </code></pre> <p>which is clearer if not as short.</p>
31,275,672
How to install dwm in Arch Linux
<p>I installed <a href="https://en.wikipedia.org/wiki/Dwm" rel="nofollow noreferrer">dwm</a> 6.0 using the file provided <a href="http://dwm.suckless.org/" rel="nofollow noreferrer">here</a> and then...</p> <pre><code># make install # dwm </code></pre> <p>But running &quot;dwm&quot; gives error: &quot;<em>dwm: cannot open display</em>&quot;. I tried &quot;exec dwm&quot;, but it starts a new login dialog, basically a new session.</p> <p>Note: I installed a display manager, and I'm sure it's not a graphics card installation problem, because I tried the &quot;awesome&quot; window manager package and it worked.</p>
58,160,362
1
3
null
2015-07-07 17:39:05.607 UTC
10
2022-02-10 00:18:59.973 UTC
2022-02-10 00:15:47.877 UTC
null
63,550
null
4,487,401
null
1
6
linux|archlinux|window-managers|dwm
30,074
<p>First, you will need to install X server and Git (as root)</p> <pre><code>pacman -S xorg-xinit xorg git </code></pre> <p>Change directory to <em>/usr/src</em> because you want this to apply to all users:</p> <pre><code>cd /usr/src </code></pre> <p>As root, clone suckless software such as dwm (window manager), st (recommended terminal), and dmenu (simple application menu)</p> <pre><code>git clone git://git.suckless.org/dwm git clone git://git.suckless.org/st git clone git://git.suckless.org/dmenu </code></pre> <p>Change directory into each one, and compile them:</p> <pre><code>cd dwm ## Do this step also with st and dmenu sudo make clean install </code></pre> <p>Add a new user that is under the users group (as root):</p> <pre><code>useradd -m -g users ari passwd ari </code></pre> <p>Log out, log in as new user, and execute:</p> <pre><code>&lt;favorite text editor&gt; .xinitrc from there, add &quot;exec dwm&quot; into the file, save, and exit </code></pre> <p>Start your session with:</p> <pre><code>startx </code></pre>
17,985,216
Simpler way to draw a circle with tkinter?
<p>Drawing a circle on a <code>tkinter Canvas</code> is usually done by the <code>create_oval</code> method. However, supplying the bounding box is often a confusing way to think about drawing a circle. It's not particularly difficult to come up with a shortcut for it, but I couldn't find anyone else doing something similar, so I'll post it in the hopes someone else finds it useful.</p>
17,985,217
2
0
null
2013-08-01 04:19:40.14 UTC
9
2022-08-17 08:16:23.107 UTC
2021-08-09 17:56:20.79 UTC
null
355,230
null
1,086,127
null
1
29
python|tkinter|geometry
106,826
<p>Here's a trick known as <a href="https://stackoverflow.com/questions/5626193/what-is-monkey-patching">monkey patching</a> where we actually add a member to the <code>tkinter</code>/<code>Tkinter</code> class <code>Canvas</code>. Below is a fully-functioning program (Python 2.7 and 3.x), of which the third paragraph is of interest. Add it to your code and you can treat <code>tk.Canvas.create_circle(x, y, r, options...)</code> as you would a builtin method, where the options are the same as <code>create_oval</code>. We do something similar for <code>create_arc</code> (fourth paragraph), and give the option to specify an <code>end</code> angle instead of an <code>extent</code>.</p> <pre><code>try: import tkinter as tk except ImportError: import Tkinter as tk # Python 2 root = tk.Tk() canvas = tk.Canvas(root, width=200, height=200, borderwidth=0, highlightthickness=0, bg=&quot;black&quot;) canvas.grid() def _create_circle(self, x, y, r, **kwargs): return self.create_oval(x-r, y-r, x+r, y+r, **kwargs) tk.Canvas.create_circle = _create_circle def _create_circle_arc(self, x, y, r, **kwargs): if &quot;start&quot; in kwargs and &quot;end&quot; in kwargs: kwargs[&quot;extent&quot;] = kwargs[&quot;end&quot;] - kwargs[&quot;start&quot;] del kwargs[&quot;end&quot;] return self.create_arc(x-r, y-r, x+r, y+r, **kwargs) tk.Canvas.create_circle_arc = _create_circle_arc canvas.create_circle(100, 120, 50, fill=&quot;blue&quot;, outline=&quot;#DDD&quot;, width=4) canvas.create_circle_arc(100, 120, 48, fill=&quot;green&quot;, outline=&quot;&quot;, start=45, end=140) canvas.create_circle_arc(100, 120, 48, fill=&quot;green&quot;, outline=&quot;&quot;, start=275, end=305) canvas.create_circle_arc(100, 120, 45, style=&quot;arc&quot;, outline=&quot;white&quot;, width=6, start=270-25, end=270+25) canvas.create_circle(150, 40, 20, fill=&quot;#BBB&quot;, outline=&quot;&quot;) root.title(&quot;Circles and Arcs&quot;) root.mainloop() </code></pre> <p>Result:</p> <p><img src="https://i.stack.imgur.com/dNw8v.png" alt="result of code" /></p>
41,003,470
npm install the exact package version specified in package.json
<p>Currently, If I run <code>npm install</code>, it installs the updated version of already installed packages. How can I install the exact version as specified in the <code>package.json</code> file?</p>
41,003,507
3
2
null
2016-12-06 19:39:12.607 UTC
10
2022-07-16 20:04:05.813 UTC
2019-03-28 17:06:39.397 UTC
null
2,942,471
null
2,179,380
null
1
96
javascript|node.js|meteor|npm|npm-install
96,740
<p>That behavior is really driven by the one specifying the versions in the package.json. If the version number looks like "1.0.0", without any other symbols, the exact version (1.0.0) should be installed.</p> <p>So what you could do is simply modify the package.json and run a <code>npm install</code> then. Be sure to clear out the node_modules directory before you do that.</p> <p><a href="https://docs.npmjs.com/files/package.json#dependencies" rel="noreferrer">https://docs.npmjs.com/files/package.json#dependencies</a></p>
2,229,341
Mercurial Server on Apache/Windows
<p>I'm searching for info to setup a Mercurial Server for Windows (7 or XP) with an Apache (xampp if it is useful to know it) with the Push Model, just like in <a href="https://stackoverflow.com/questions/740075/mercurial-server">this question</a> but my team is composed of 5 to 8 (unsolvent) guys who are each one working in separated places, so I don't think the bitbucket solution or anyother non-private repo out there.</p> <p>I think <a href="http://mercurial.selenic.com/wiki/HgWebDirStepByStep" rel="nofollow noreferrer">this post</a> would do the trick, but i haven't experienced anything with cgi before, </p> <p>Has anybody done this before? where can I find a more detailed explanation? thanks in advance </p> <p>[EDIT]</p> <p>I'm now getting this error: Premature end of script headers: hgwebdir.cgi</p> <p>The log error says "no module named mercurial"</p> <p>this is my hgwebdir.cgi file</p> <pre><code>#!c:/python24/python.exe # # An example CGI script to export multiple hgweb repos, edit as necessary # adjust python path if not a system-wide install: import sys sys.path.insert(0, "c:/mercurial_library") # enable importing on demand to reduce startup time from mercurial import demandimport; demandimport.enable() # Uncomment to send python tracebacks to the browser if an error occurs: #import cgitb #cgitb.enable() # If you'd like to serve pages with UTF-8 instead of your default # locale charset, you can do so by uncommenting the following lines. # Note that this will cause your .hgrc files to be interpreted in # UTF-8 and all your repo files to be displayed using UTF-8. # #import os #os.environ["HGENCODING"] = "UTF-8" from mercurial.hgweb.hgwebdir_mod import hgwebdir import mercurial.hgweb.wsgicgi as wsgicgi application = hgwebdir('hgweb.config') wsgicgi.launch(application) </code></pre>
2,235,343
3
3
null
2010-02-09 13:30:35.727 UTC
9
2017-06-19 10:08:51.903 UTC
2017-05-23 12:09:10.833 UTC
null
-1
null
76,832
null
1
5
windows|apache|mercurial
7,967
<p>I used the <a href="https://www.mercurial-scm.org/wiki/HgWebDirStepByStep" rel="nofollow noreferrer">HgWebDir instructions</a>:</p> <p>Here is my httpd.conf piece for the mercurial sites (slightly edited):</p> <pre><code>&lt;VirtualHost *:88&gt; ServerName hg.example.com DocumentRoot c:/apache_sites/hg RewriteEngine on RewriteRule ^/$ /public [R] RewriteRule ^/public(.*) /public/hgwebdir.cgi$1 [L] RewriteRule ^/private(.*) /private/hgwebdir.cgi$1 [L] # mod_alias alternative (pretty url's) &lt;Directory c:/apache_sites/hg &gt; Order allow,deny Allow from all AllowOverride All Options ExecCGI AddHandler cgi-script .cgi &lt;/Directory&gt; &lt;Location /private/&gt; AuthType Digest AuthName "hg.example.com" AuthDigestProvider file AuthUserFile c:/apache_sites/hg/hgusers AuthGroupFile c:/apache_sites/hg/hggroup AuthDigestDomain /private/ Require group owner &lt;/Location&gt; &lt;Location /public/&gt; AuthType Digest AuthName "hg.example.com" AuthDigestProvider file AuthUserFile c:/apache_sites/hg/hgusers AuthGroupFile c:/apache_sites/hg/hggroup AuthDigestDomain /public/ &lt;LimitExcept GET&gt; Require group developer &lt;/LimitExcept&gt; &lt;/Location&gt; LogLevel debug ErrorLog "c:/apache/logs/hg-error.log" CustomLog "c:/apache/logs/hg-access.log" combined LogLevel debug &lt;/VirtualHost&gt; # vim:se ft=apache: </code></pre> <p>I also had to turn on a few modules for Auth Digest, etc.</p> <p>I put the hgwebdir.cgi in the root of the public and the private folders, and just put each of my hg repos in the repos subfolder under the appropriate folders.</p> <p>Apache authentication took care of my authorization.</p> <p>Then I just put a hgweb.config file in the same locations like this:</p> <pre><code>[collections] repos = repos [web] allow_archive = bz2 gz zip style = gitweb baseurl = /public </code></pre> <p><strong>Updated Question</strong></p> <p>The mercurial packages need to be on the PYTHON_PATH</p> <p><a href="https://stackoverflow.com/questions/2123798/error-setting-up-mercurial-on-windows-server-2008/2129114#2129114">This answer</a> gives more detail.</p>
1,464,919
What is unexpected T_VARIABLE in PHP?
<p>I get this PHP error:</p> <blockquote> <p>Parse error: syntax error, unexpected T_VARIABLE</p> </blockquote> <p>From this line:</p> <pre><code>$list[$i][$docinfo['attrs']['@groupby']] = $docinfo['attrs']['@count']; </code></pre> <p>Is there anything wrong with this line?</p>
1,464,941
3
1
null
2009-09-23 09:26:46.403 UTC
17
2020-04-23 10:35:31.783 UTC
2014-08-07 20:24:48.29 UTC
null
445,131
null
104,015
null
1
96
php|syntax-error
321,640
<p>There might be a semicolon or bracket missing a line before your pasted line.</p> <p>It seems fine to me; every string is allowed as an array index.</p>
8,971,160
What is the exhaustive list of all "android.intent.action" actions available in the Android SDK?
<p>Hi fellows,</p> <p>I'd like to know if there is some exhaustive reference of all Intent actions defined in the standard Android SDK ? I'm thinking of the full "android.intent.action.someaction" names, not the restricted list of conveniently aliased actions defined in the Intent class, e.g Intent.ACTION_VIEW, Intent.ACTION_POWER_CONNECTED, etc...</p> <p>For those who believe all Intent actions are aliased in the Intent class (I was one of them until very recently) I have at least one action which is not : android.intent.action.HDMI_PLUG (defined in media/java/android/media/AudioService.java) and I believe there are many others.</p> <p>But I could not find some exhaustive list in the Android Reference, so maybe if you can direct me to some place I can find it ?</p> <p>Thanks !</p> <p>--- UPDATE 23/01/2012 15h36 ---</p> <p>Thanks to CommonsWare for mentioning HDMI_PLUG is not at all part of the Android SDk... it was a bad example, but still, there are intents that are not defined in Intent.java, such as TelephonyManager.ACTION_PHONE_STATE_CHANGED.</p>
8,986,165
4
1
null
2012-01-23 11:51:57.433 UTC
19
2017-09-12 13:08:49.857 UTC
2012-01-24 11:37:22.873 UTC
null
1,160,527
null
1,160,527
null
1
34
android|android-intent|action
42,382
<p>Hey I think I answered my own question :)</p> <p>In my Android SDK directory, under /platforms/android-x/data (x being the API level) I've found several very interesting files:</p> <ul> <li>activity_actions.txt</li> <li>broadcast_actions.txt</li> <li>categories.txt</li> <li>features.txt</li> <li>widgets.txt</li> </ul> <p>Turns out the first two contain plenty of raw Intents, including ones that are not defined in Intent.java !</p> <p>I'm not quite sure what theses lists are here for, I'd just like to be sure they are exhaustive for their API level... (even if I don't see why they wouldn't be)</p>
19,433,366
Running java in package from command line
<p>I have read the previously posted questions. Some are vague and none solved my problem so I am forced to ask again.</p> <p>I have two simple classes,</p> <pre><code>package One; import One.Inner.MyFrame; public class test { public static void main(String args[]) { MyFrame f= new MyFrame(); } } </code></pre> <p>And the other class is, </p> <pre><code>package One.Inner; import java.awt.*; import javax.swing.*; public class MyFrame extends JFrame { public MyFrame() { setPreferredSize(new Dimension(400,560)); setVisible(true); } } </code></pre> <p>I am at base folder "basic" in Windows cmd. I compile using</p> <pre class="lang-none prettyprint-override"><code>basic&gt; javac *.java -d . </code></pre> <p>A folder and subfolder is created.</p> <pre class="lang-none prettyprint-override"><code>cd One basic\One&gt; java test </code></pre> <p>This generates a big set of errors. Many answers directed to specify the full path which didn't work. My classes are in One so specifying One using -cp didn't work either.</p>
19,433,387
5
1
null
2013-10-17 17:28:14.047 UTC
12
2018-07-22 21:06:26.493 UTC
2017-09-07 14:41:22.98 UTC
null
330,315
null
2,756,339
null
1
40
java|command-line|package|classpath|javac
108,176
<p>You'd run it as:</p> <pre><code>java One.Test </code></pre> <p>... but from the <em>root</em> directory (<code>basic</code>), <em>not</em> from the <code>One</code> directory. You always specify the <em>fully-qualified</em> class name.</p> <p>Oh, and package names in Java should be lower-case, so it should be <code>one</code> and <code>one.inner</code>, not <code>One</code> and <code>One.Inner</code>. Just a convention, but one which pretty much everyone follows.</p>
19,719,911
Getting user-space stack information from perf
<p>I'm currently trying to track down some phantom I/O in a PostgreSQL build I'm testing. It's a multi-process server and it isn't simple to associate disk I/O back to a particular back-end and query.</p> <p>I thought Linux's <code>perf</code> tool would be ideal for this, but I'm struggling to capture block I/O performance counter metrics and associate them with user-space activity.</p> <p>It's easy to record block I/O requests and completions with, eg:</p> <pre><code>sudo perf record -g -T -u postgres -e 'block:block_rq_*' </code></pre> <p>and the user-space pid is recorded, but there's no kernel or user-space stack captured, or ability to snapshot bits of the user-space process's heap (say, query text) etc. So while you have the pid, you don't know what the process was doing at that point. Just <code>perf script</code> output like:</p> <pre><code>postgres 7462 [002] 301125.113632: block:block_rq_issue: 8,0 W 0 () 208078848 + 1024 [postgres] </code></pre> <p>If I add the <code>-g</code> flag to <code>perf record</code> it'll take snapshots of the <em>kernel</em> stack, but doesn't capture user-space state for perf events captured in the kernel. The user-space stack only goes up to the entry-point from userspace, like <code>LWLockRelease</code>, <code>LWLockAcquire</code>, <code>memcpy</code> (mmap'd IO), <code>__GI___libc_write</code>, etc.</p> <p>So. Any tips? Being able to capture a snapshot of the <em>user-space</em> stack in response to <em>kernel</em> events would be ideal.</p> <p>I'm on Fedora 19, 3.11.3-201.fc19.x86_64, Schrödinger’s Cat, with perf version 3.10.9-200.fc19.x86_64.</p>
19,720,446
1
1
null
2013-11-01 02:30:44.167 UTC
10
2014-02-04 12:48:51.24 UTC
2013-11-01 05:01:25.01 UTC
null
398,670
null
398,670
null
1
11
c|linux|linux-kernel|perf
8,431
<p>OK, looks like there are several parts to this:</p> <ul> <li><p>I'm on x86_64, where most distros build with <code>-fomit-frame-pointer</code> by default, and <code>perf</code> can't follow the stack without frame pointers;</p></li> <li><p>.... unless it's a newer version built with <code>libunwind</code> support, in which case it supports <code>perf record -g dwarf</code>.</p></li> </ul> <p>See:</p> <ul> <li><a href="http://lkml.indiana.edu/hypermail/linux/kernel/1203.3/01569.html" rel="nofollow noreferrer">the patch adding libunwind support to Perf</a></li> <li><a href="http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=725075" rel="nofollow noreferrer">Debian bug 725075</a>. </li> <li><a href="https://stackoverflow.com/questions/7031210/linux-perf-how-to-interpret-and-find-hotspots">linux perf: how to interpret and find hotspots</a></li> </ul> <p>I'm on Fedora 18, but <a href="https://bugzilla.redhat.com/show_bug.cgi?id=1025603" rel="nofollow noreferrer">the same issue applies</a>. So if you're profiling code you're working on (as is likely on Stack Overflow), rebuild with <code>-fno-omit-frame-pointer</code> and <code>-ggdb</code>.</p> <p>I landed up rebuilding <code>perf</code> because I wanted to be able to compare to the stock RPMs:</p> <ul> <li><code>sudo yum build-dep perf</code></li> <li><code>sudo yum install yum-utils rpmdevtools libunwind-devel</code></li> <li><code>yumdownloader --source perf</code> or download the appropriate <code>kernel-.....src.rpm</code> srpm</li> <li><code>rpmdev-setuptree</code></li> <li><code>rpm -Uvh kernel-*.src.rpm</code></li> <li><code>cd $HOME/rpmbuild/SPECS</code></li> <li><code>rpmbuild -bp --target=$(uname -m) kernel.spec</code></li> </ul> <p>At this point you can just build a new <code>perf</code> if you want:</p> <ul> <li><code>cd $HOME/rpmbuild/BUILD/kernel-*/linux-*/tools/perf</code></li> <li><code>make</code></li> </ul> <p>... which I did and tested that the updated <code>perf</code> does in fact capture a useful stack if built with libunwind available.</p> <p>You can also build a new rpm:</p> <ul> <li><p>edit kernel.spec, uncomment the line <code>%define buildid ...</code>, change buildid to something like <code>.perfunwind</code>. Note it's <code>%define</code> not <code>% define</code>.</p></li> <li><p>In the same spec file, find:</p> <pre><code>%global perf_make \ make %{?_smp_mflags} -C tools/perf -s V=1 WERROR=0 NO_LIBUNWIND=1 HAVE_CPLUS_DEMANGLE=1 NO_GTK2=1 NO_LIBNUMA=1 NO_STRLCPY=1 prefix=%{_prefix} </code></pre> <p>and delete <code>NO_LIBUNWIND=1</code></p></li> <li><p><code>rpmbuild -bb --without up --without mp --without pae --without debug --without doc --without headers --without debuginfo --without bootwrapper --without with_vdso_install --with perf kernel.spec</code> to produce new <code>perf</code> RPMs without building the whole kernel. Or if you want, omit the <code>--without</code> for the kernel flavour you want, in which case you'll also want to build headers, debuginfo, etc.</p></li> <li><p><code>sudo rpm -Uvh $HOME/rpmbuild/RPMS/x86_64/perf-*.fc19.x86_64.rpm</code></p></li> </ul> <p>See <a href="http://fedoraproject.org/wiki/Building_a_custom_kernel" rel="nofollow noreferrer">the fedora project guide on building a custom kernel</a>.</p> <p>I've reported the issue to Fedora; they shouldn't be using <code>NO_LIBUNWIND=1</code>. See <a href="https://bugzilla.redhat.com/show_bug.cgi?id=1025603" rel="nofollow noreferrer">bug 1025603</a>.</p> <p>Once you have a rebuilt <code>perf</code> you can use <code>perf record -g dwarf</code> to get full stacks.</p>
635,565
"Walk" JSON response and populate form fields -- more efficient approach?
<p>I know there is a far more elegant/efficient way of doing this (in php I would use foreach) but with jQuery how can I walk the var/val pairs of a JSON response and populate form fields with the same id's as the field names in the JSON response?</p> <p>Here is my JSON response:</p> <pre><code>[{"field":"svendor_name","value":"Vendor Name Inc."},{"field":"svendor_addr1","value":"1234 Vendor Lane."},{"field":"svendor_addr2","value":"Suite 100"},{"field":"svendor_city" ,"value":"Vendorville"},{"field":"svendor_state","value":"CA"},{"field":"svendor_zip","value":"90210"},{"field" :"svendor_phone","value":"800-555-1234"}] </code></pre> <p>Here is my jQuery code for populating the form:</p> <pre><code>$(document).ready(function() { $('#svendor_name').bind("change", function() { var svendor = $("#svendor_name").val(); svendor = svendor.replace(/&amp;/g, '*'); $.getJSON("get_vendors.php?sname=" + svendor, function(data) { $.each(data, function(i, item) { if(item.field == "svendor_name") { $("#svendor_name").val(item.value); } else if(item.field == "svendor_addr1") { $("#svendor_addr1").val(item.value); } else if(item.field == "svendor_addr2") { $("#svendor_addr2").val(item.value); } else if(item.field == "svendor_city") { $("#svendor_city").val(item.value); } else if(item.field == "svendor_state") { $("#svendor_state").val(item.value); } else if(item.field == "svendor_zip") { $("#svendor_zip").val(item.value); } else if(item.field == "svendor_phone") { $("#svendor_phone").val(item.value); } else if(item.field == "svendor_id") { $("#svendor_id").val(item.value); } }); }); }); }); </code></pre> <p>That all works fine and good but I really want to avoid all the if/else statements and just use the data coming back from the getJSON method to determine what fields get populated with what values. What is a cleaner/more effective approach to this?</p> <p>-- Nicholas</p>
635,575
4
0
null
2009-03-11 17:31:22.803 UTC
10
2010-10-28 16:48:28.547 UTC
null
null
null
Nicholas Kreidberg
59,975
null
1
7
jquery|json
9,113
<p>You can get rid of all "if" statements by replacing your $.each with this:</p> <pre><code>$.each(data, function(i, item){ $("#"+item.field).val(item.value); }); </code></pre>
624,854
static_cast with boost::shared_ptr?
<p>What is the equivalent of a <code>static_cast</code> with <code>boost::shared_ptr</code>?</p> <p>In other words, how do I have to rewrite the following </p> <pre><code>Base* b = new Derived(); Derived* d = static_cast&lt;Derived*&gt;(b); </code></pre> <p>when using <code>shared_ptr</code>?</p> <pre><code>boost::shared_ptr&lt;Base&gt; b(new Derived()); boost::shared_ptr&lt;Derived&gt; d = ??? </code></pre>
624,858
4
1
null
2009-03-09 02:47:21.667 UTC
23
2014-08-12 09:52:31.09 UTC
2014-08-12 09:52:31.09 UTC
Kristo
31,317
null
60,628
null
1
73
c++|boost|shared-ptr|static-cast
43,446
<p>Use <code>boost::static_pointer_cast</code>:</p> <pre><code>boost::shared_ptr&lt;Base&gt; b(new Derived()); boost::shared_ptr&lt;Derived&gt; d = boost::static_pointer_cast&lt;Derived&gt;(b); </code></pre>
40,100,176
Can dask parralelize reading fom a csv file?
<p>I'm converting a large textfile to a hdf storage in hopes of a faster data access. The conversion works allright, however reading from the csv file is not done in parallel. It is really slow (takes about 30min for a 1GB textfile on an SSD, so my guess is that it is not IO-bound). </p> <p>Is there a way to have it read in multiple threads in parralel? Sice it might be important, I'm currently forced to run under Windows -- just in case that makes any difference.</p> <pre><code>from dask import dataframe as ddf df = ddf.read_csv("data/Measurements*.csv", sep=';', parse_dates=["DATETIME"], blocksize=1000000, ) df.categorize([ 'Type', 'Condition', ]) df.to_hdf("data/data.hdf", "Measurements", 'w') </code></pre>
40,107,654
2
1
null
2016-10-18 05:27:31.93 UTC
15
2019-05-24 14:26:13.51 UTC
null
null
null
null
1,692,072
null
1
32
python|csv|pandas|dask
25,730
<p>Yes, dask.dataframe can read in parallel. However you're running into two problems:</p> <h3>Pandas.read_csv only partially releases the GIL</h3> <p>By default dask.dataframe parallelizes with threads because most of Pandas can run in parallel in multiple threads (releases the GIL). Pandas.read_csv is an exception, especially if your resulting dataframes use object dtypes for text</p> <h3>dask.dataframe.to_hdf(filename) forces sequential computation</h3> <p>Writing to a single HDF file will force sequential computation (it's very hard to write to a single file in parallel.)</p> <h3>Edit: New solution</h3> <p>Today I would avoid HDF and use Parquet instead. I would probably use the multiprocessing or dask.distributed schedulers to avoid GIL issues on a single machine. The combination of these two should give you full linear scaling.</p> <pre><code>from dask.distributed import Client client = Client() df = dask.dataframe.read_csv(...) df.to_parquet(...) </code></pre> <h3>Solution</h3> <p>Because your dataset likely fits in memory, use dask.dataframe.read_csv to load in parallel with multiple processes, then switch immediately to Pandas.</p> <pre><code>import dask.dataframe as ddf import dask.multiprocessing df = ddf.read_csv("data/Measurements*.csv", # read in parallel sep=';', parse_dates=["DATETIME"], blocksize=1000000, ) df = df.compute(get=dask.multiprocessing.get) # convert to pandas df['Type'] = df['Type'].astype('category') df['Condition'] = df['Condition'].astype('category') df.to_hdf('data/data.hdf', 'Measurements', format='table', mode='w') </code></pre>
22,221,277
Bash, grep between two lines with specified string
<p>Example:</p> <pre><code>a43 test1 abc cvb bnm test2 kfo </code></pre> <p>I need all lines between test1 and test2. Normal grep does not work in this case. Do you have any propositions?</p>
22,222,219
8
1
null
2014-03-06 10:12:49.417 UTC
22
2020-01-06 22:57:20.537 UTC
null
null
null
null
3,162,968
null
1
68
regex|bash|grep
92,875
<blockquote> <p>Print from <code>test1</code> to <code>test2</code> (Trigger lines included)</p> </blockquote> <pre><code>awk '/test1/{f=1} /test2/{f=0;print} f' awk '/test1/{f=1} f; /test2/{f=0}' awk '/test1/,/test2/' </code></pre> <p> <pre><code>test1 abc cvb bnm test2 </code></pre> <hr> <blockquote> <p>Prints data between <code>test1</code> to <code>test2</code> (Trigger lines excluded)</p> </blockquote> <pre><code>awk '/test1/{f=1;next} /test2/{f=0} f' awk '/test2/{f=0} f; /test1/{f=1}' </code></pre> <p> <pre><code>abc cvb bnm </code></pre>
23,517,139
java.lang.ClassCastException: com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnectionOldImpl cannot be cast to javax.net.ssl.HttpsURLConnection
<p>I tried this code in my Netbeans 7.4 and it works without problem</p> <pre><code>import java.io.IOException; import java.net.URL; import javax.net.ssl.HttpsURLConnection; public class JavaApplication148 { public static void main(String[] args) throws IOException { URL url = new URL("https://redmine.ackee.cz/time_entries.xml"); HttpsURLConnection httpCon = (HttpsURLConnection) url.openConnection(); } } </code></pre> <p>However then I used it in eclipse in my maven-driven project and it throws following exception :</p> <pre><code>java.lang.ClassCastException: com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnectionOldImpl cannot be cast to javax.net.ssl.HttpsURLConnection </code></pre> <p>This is following class in my maven project that throws an error</p> <pre><code>package cz.ackee.redmine.commands; import java.io.IOException; import java.net.URL; import javax.net.ssl.HttpsURLConnection; public abstract class RedmineCommand { public void write(String xmlAddress, String text, String requestMethod) throws IOException{ URL url = new URL("https://redmine.xxx.cz/time_entries.xml"); HttpsURLConnection httpCon = (HttpsURLConnection) url.openConnection(); //this line throws exception } } </code></pre> <p>This is my pom.xml</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;cz.ackee&lt;/groupId&gt; &lt;artifactId&gt;pan-unicorn-bot&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;name&gt;Pan Unicorn Bot&lt;/name&gt; &lt;description&gt;Pan unicorn IRC Bot&lt;/description&gt; &lt;repositories&gt; &lt;repository&gt; &lt;id&gt;apache-snapshots&lt;/id&gt; &lt;url&gt;http://repository.apache.org/snapshots/&lt;/url&gt; &lt;/repository&gt; &lt;/repositories&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;mysql&lt;/groupId&gt; &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt; &lt;version&gt;5.1.30&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt; &lt;version&gt;4.3.5.Final&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.commons&lt;/groupId&gt; &lt;artifactId&gt;commons-cli&lt;/artifactId&gt; &lt;version&gt;1.3-SNAPSHOT&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.taskadapter&lt;/groupId&gt; &lt;artifactId&gt;redmine-java-api&lt;/artifactId&gt; &lt;version&gt;1.23&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;properties&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt; &lt;/properties&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;version&gt;2.3&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;1.7&lt;/source&gt; &lt;target&gt;1.7&lt;/target&gt; &lt;downloadSources&gt;true&lt;/downloadSources&gt; &lt;downloadJavadocs&gt;true&lt;/downloadJavadocs&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-assembly-plugin&lt;/artifactId&gt; &lt;version&gt;2.2.1&lt;/version&gt; &lt;configuration&gt; &lt;descriptors&gt; &lt;descriptor&gt;/src/main/assembly/binary.xml&lt;/descriptor&gt; &lt;/descriptors&gt; &lt;/configuration&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;make-assembly&lt;/id&gt; &lt;phase&gt;package&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;single&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt; &lt;version&gt;2.3.2&lt;/version&gt; &lt;configuration&gt; &lt;archive&gt; &lt;index&gt;true&lt;/index&gt; &lt;manifest&gt; &lt;addClasspath&gt;true&lt;/addClasspath&gt; &lt;mainClass&gt;cz.ackee.unicorn.PanUnicornMain&lt;/mainClass&gt; &lt;/manifest&gt; &lt;manifestEntries&gt; &lt;mode&gt;development&lt;/mode&gt; &lt;url&gt;${project.url}&lt;/url&gt; &lt;key&gt;value&lt;/key&gt; &lt;/manifestEntries&gt; &lt;/archive&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>Any idea, why it does compile and run without problem on netbeans and why it does not go well on maven-eclipse project?</p> <p>(I compile through command line using <code>mvn package</code>, I run it through eclipse)</p>
23,518,852
4
2
null
2014-05-07 11:55:22.537 UTC
4
2021-10-29 09:45:43.19 UTC
2014-05-10 10:50:08 UTC
null
2,854,908
null
2,854,908
null
1
17
java|eclipse|maven|netbeans|classnotfoundexception
62,752
<p>The solution is to change this line </p> <pre><code>URL url = new URL("https://redmine.xxx.cz/time_entries.xml"); </code></pre> <p>into this line</p> <pre><code>URL url = new URL(null, "https://redmine.xxx.cz/time_entries.xml", new sun.net.www.protocol.https.Handler()); </code></pre>
42,754,388
Uncaught (in promise) TypeError: Failed to fetch and Cors error
<p>having a problem with getting data back from database. I am trying my best to explain the problem.</p> <p>1.If I leave "mode":"no-cors" inside the code below, then I can get data back from server with Postman, but not with from my own server. Thinking it has to be my client side error</p> <ol start="2"> <li>When I remove "mode":"no-cors" then I am getting 2 errors: -Fetch API cannot load <a href="http://localhost:3000/" rel="noreferrer">http://localhost:3000/</a>. Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. -Uncaught (in promise) TypeError: Failed to fetch</li> </ol> <p>Quick Browsing suggested to put in the "mode":"no-cors" which fixed this error, but it does not feel right thing to do.</p> <p>So I thought maybe somebody has a suggestion how to approach this problem.</p> <p>Really hope I was clear enough, but pretty sure I am not giving clear explanation here :S</p> <pre><code>function send(){ var myVar = {"id" : 1}; console.log("tuleb siia", document.getElementById('saada').value); fetch("http://localhost:3000", { method: "POST", headers: { "Access-Control-Allow-Origin": "*", "Content-Type": "text/plain" },//"mode" : "no-cors", body: JSON.stringify(myVar) //body: {"id" : document.getElementById('saada').value} }).then(function(muutuja){ document.getElementById('väljund').innerHTML = JSON.stringify(muutuja); }); } </code></pre>
42,754,558
7
5
null
2017-03-12 23:21:35.84 UTC
14
2022-07-21 00:25:27.693 UTC
2017-03-12 23:28:59.587 UTC
null
4,177,642
null
4,177,642
null
1
45
javascript|node.js|cors
277,341
<p>Adding <code>mode:'no-cors'</code> to the request header guarantees that no response will be available in the response</p> <p>Adding a "non standard" header, line <code>'access-control-allow-origin'</code> will trigger a OPTIONS preflight request, which your server must handle correctly in order for the POST request to even be sent</p> <p>You're also doing <code>fetch</code> wrong ... <code>fetch</code> returns a "promise" for a <code>Response</code> object which has promise creators for <code>json</code>, <code>text</code>, etc. depending on the content type... </p> <p>In short, if your server side handles CORS correctly (which from your comment suggests it does) the following should work</p> <pre><code>function send(){ var myVar = {"id" : 1}; console.log("tuleb siia", document.getElementById('saada').value); fetch("http://localhost:3000", { method: "POST", headers: { "Content-Type": "text/plain" }, body: JSON.stringify(myVar) }).then(function(response) { return response.json(); }).then(function(muutuja){ document.getElementById('väljund').innerHTML = JSON.stringify(muutuja); }); } </code></pre> <p>however, since your code isn't really interested in JSON (it stringifies the object after all) - it's simpler to do</p> <pre><code>function send(){ var myVar = {"id" : 1}; console.log("tuleb siia", document.getElementById('saada').value); fetch("http://localhost:3000", { method: "POST", headers: { "Content-Type": "text/plain" }, body: JSON.stringify(myVar) }).then(function(response) { return response.text(); }).then(function(muutuja){ document.getElementById('väljund').innerHTML = muutuja; }); } </code></pre>
25,654,805
Keep inner interface method names in proguard
<p>Lets say I have..</p> <pre><code>public class SomeClass { public interface someInterface { public void firstMethod(String variable); public void secondMethod(String variable); public void thirdMethod(); } } </code></pre> <p>and I do..</p> <pre><code>-keep,includedescriptorclasses public class com.somepackage.SomeClass { &lt;fields&gt;; &lt;methods&gt;; } -keep public interface com.somepackage.someInterface {*;} </code></pre> <p>I end up with </p> <pre><code>public interface someInterface { public void a(String variable); public void a(String variable); public void a(); } </code></pre> <p>How do I ensure this interface's method names are not obfuscated while still obfuscating the rest of the class? </p>
25,711,830
3
1
null
2014-09-03 22:47:26.253 UTC
5
2019-10-21 13:35:29.89 UTC
2014-09-04 00:16:34.943 UTC
null
1,154,026
null
1,154,026
null
1
28
java|android|proguard
17,361
<p>ProGuard uses the naming convention of Java bytecode, as seen in class file names and stacktraces. Therefore:</p> <pre><code>-keep public interface com.somepackage.SomeClass$someInterface {*;} </code></pre>
30,554,953
How to animate FloatingActionButton of new Design Support Library
<p>I am using a TabLayout with 5 different fragments. On 3 of these fragments a <code>android.support.design.widget.FloatingActionButton</code> should appear. Right now I simply set the visibility of the FAB when the tab changes, but I would like to have an animation, where the FAB comes in and out. How can I achieve this in Android?</p>
30,576,441
5
1
null
2015-05-31 07:28:47.62 UTC
9
2015-08-16 20:09:03.443 UTC
2015-05-31 09:57:27.64 UTC
null
2,619,912
null
4,496,411
null
1
15
android|android-animation|floating-action-button|android-design-library
21,551
<p>Because I did not want to extend the <code>FloatingActionButton</code>, I made it this way:</p> <pre><code>FloatingActionButton createButton; // ... Animation makeInAnimation = AnimationUtils.makeInAnimation(getBaseContext(), false); makeInAnimation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationStart(Animation animation) { createButton.setVisibility(View.VISIBLE); } }); Animation makeOutAnimation = AnimationUtils.makeOutAnimation(getBaseContext(), true); makeOutAnimation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationEnd(Animation animation) { createButton.setVisibility(View.INVISIBLE); } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationStart(Animation animation) { } }); // ... if (createButton.isShown()) { createButton.startAnimation(makeOutAnimation); } // ... if (!createButton.isShown()) { createButton.startAnimation(makeInAnimation); } </code></pre>
65,919,460
The author primary signature's timestamp found a chain building issue: UntrustedRoot: self signed certificate in certificate chain
<p>While doing a docker build on my .NET Core project, I got the following error on all my NuGets:</p> <blockquote> <p>80.19 /app/GradingTool.Tests/GradingTool.Tests.csproj : error NU3028: Package 'Microsoft.EntityFrameworkCore 5.0.0' from source 'https://api.nuget.org/v3/index.json': The author primary signature's timestamp found a chain building issue: UntrustedRoot: self signed certificate in certificate chain [/app/GradingTool.sln]</p> <p>#12 80.20 /app/GradingTool.Tests/GradingTool.Tests.csproj : error NU3037: Package 'Microsoft.EntityFrameworkCore 5.0.0' from source 'https://api.nuget.org/v3/index.json': The author primary signature validity period has expired. [/app/GradingTool.sln]</p> <p>#12 80.20 /app/GradingTool.Tests/GradingTool.Tests.csproj : error NU3028: Package 'Microsoft.EntityFrameworkCore 5.0.0' from source 'https://api.nuget.org/v3/index.json': The repository countersignature's timestamp found a chain building issue: UntrustedRoot: self signed certificate in certificate chain [/app/GradingTool.sln]</p> </blockquote> <p>I never had this error before, Can someone help me figure out what the problem is?</p> <p>Dockerfile:</p> <pre><code>FROM mcr.microsoft.com/dotnet/sdk:latest AS build-env WORKDIR /app RUN apt-get update -yq \ &amp;&amp; apt-get install curl gnupg -yq \ &amp;&amp; curl -sL https://deb.nodesource.com/setup_10.x | bash \ &amp;&amp; apt-get install nodejs -yq # Copy csproj and restore as distinct layers COPY . ./ RUN dotnet restore RUN dotnet publish -c Release -o out # Build runtime image FROM mcr.microsoft.com/dotnet/aspnet:latest RUN apt-get update \ &amp;&amp; apt-get install -y --no-install-recommends libgdiplus libc6-dev \ &amp;&amp; apt-get clean \ &amp;&amp; rm -rf /var/lib/apt/lists/* WORKDIR /app COPY --from=build-env /app/out . ENV ASPNETCORE_URLS=&quot;http://+:4200&quot; ENV ASPNETCORE_ENVIRONMENT=&quot;Production&quot; ENV GOOGLE_APPLICATION_CREDENTIALS=&quot;Credentials/SchoolTools-e9f260bdf56e.json&quot; ENV VIRTUAL_HOST=&quot;eva.schooltools.lu,www.eva.schooltools.lu,schooltools.lu,www.schooltools.lu&quot; ENV LETSENCRYPT_HOST=&quot;eva.schooltools.lu,www.eva.schooltools.lu,schooltools.lu,www.schooltools.lu&quot; ENV LETSENCRYPT_EMAIL=&quot;[email protected]&quot; EXPOSE 4200 ENTRYPOINT [&quot;dotnet&quot;, &quot;GradingTool.dll&quot;] </code></pre>
65,926,394
9
6
null
2021-01-27 12:44:37.603 UTC
6
2021-09-17 08:51:56.65 UTC
2021-01-29 06:16:55.127 UTC
null
1,402,846
null
10,667,460
null
1
96
.net|docker|ssl|.net-core|nuget
19,965
<p>In the Dockerfile file, I changed from</p> <pre><code>FROM mcr.microsoft.com/dotnet/aspnet:5.0-buster-slim </code></pre> <p>to</p> <pre><code>FROM mcr.microsoft.com/dotnet/sdk:5.0-alpine </code></pre> <p>This worked for me!</p>
13,922,415
How do I setup Oracle ODBC drivers on RHEL 6/Linux
<p>I need to setup Oracle ODBC drivers on RHEL 6 to connect to an Oracle data source residing on a remote Windows machine. </p> <p>I have taken the following steps:<br> [1] Installed oracle-instanceclient-basic<br> [2] Set environment variables: ORACLE_HOME and LD path<br> [3] Created /etc/oracle/TNSnames.ora and configured but it did not set it correctly</p> <p>Initially, I got the error, <code>"Connect failed because target or object does not exist"</code></p> <p>Then, I set: <code>ORACLE_SID = DB_NAME</code> in the TNSnames.ora file.</p> <p>But, that did not fix the issue, I got a new error message now: <code>"TNS: net service name is incorrectly specified"</code></p>
13,935,571
2
1
null
2012-12-17 21:23:49.19 UTC
8
2015-01-15 04:05:31.693 UTC
2014-10-02 12:55:27.813 UTC
null
3,776,858
null
862,163
null
1
5
linux|oracle|odbc|drivers|rhel6
46,234
<pre><code>yum install unixODBC rpm -ivh oracle-instantclient-basic-10.2.0.3-1.i386.rpm #downloaded on http://www.oracle.com/technology/software/tech/oci/instantclient/htdocs/linuxsoft.html unzip instantclient-odbc-linux32-10.2.0.3-20061115.zip #downloaded on http://www.oracle.com/technology/software/tech/oci/instantclient/htdocs/linuxsoft.html cp ./instantclient_10_2/libsqora.so.10.1 /usr/lib/oracle/10.2.0.3/client/lib/ export ORACLE_HOME=/usr/lib/oracle/10.2.0.3/client export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME/lib </code></pre> <p>Also you need to set <code>$TWO_TASK</code> (default location where Oracle is looking to pickup the server) to point to where the Oracle server is running on Windows - - don't forget to add the listener at the end after the port number:</p> <pre><code>export TWO_TASK=//213.123.23.19:1521/listener </code></pre> <p>To chech for the name of listener, type the following commands on the windows prompt that is running the Oracle server:</p> <pre><code>lsnrctl status </code></pre> <p>It will enlist listeners and their state (READY or UNKNOWN). Connect to the listener that is in the ready state: <code>Instance "zelistener", status READY</code></p> <p>mkdir /etc/oracle</p> <p>vi /etc/oracle/tnsnames.ora</p> <pre><code>MY_SID = ( DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP) (Host = 127.0.0.1) (Port = 1521) ) ) (CONNECT_DATA = (SID = MY_SID) ) ) </code></pre> <p>export TNS_ADMIN=/etc/oracle</p> <p>vi /etc/odbcinst.ini</p> <pre><code>[OracleODBC-10g] Description = Oracle ODBC driver for Oracle 10g Driver = /usr/lib/oracle/10.2.0.3/client/lib/libsqora.so.10.1 FileUsage = 1 Driver Logging = 7 </code></pre> <p>vi /etc/odbc.ini</p> <pre><code>[simple] Driver = OracleODBC-10g DSN = OracleODBC-10g ServerName = MY_SID UserID = USER Password = PASSWORD </code></pre> <p>isql -v simple</p> <pre><code>+---------------------------------------+ | Connected! | | | | sql-statement | | help [tablename] | | quit | | | +---------------------------------------+ </code></pre>
25,387,951
Curious issue with Oracle UNION and ORDER BY
<p>The following query is <a href="http://sqlfiddle.com/#!4/d41d8/34078">perfectly valid</a> in pretty much every database (give or take a <code>dual</code> dummy table), including Oracle:</p> <pre><code>select 'A' as x from dual union all select 'B' from dual order by x asc </code></pre> <p>Returning:</p> <pre><code>| X | |---| | A | | B | </code></pre> <p>Now this query is still quite standard SQL, but <a href="http://sqlfiddle.com/#!4/d41d8/34079">doesn't work</a> on Oracle</p> <pre><code>select 'A' as x from dual union all select 'B' from dual union all select 'C' from dual order by x asc </code></pre> <p>I'm getting</p> <pre><code>ORA-00904: "X": invalid identifier </code></pre> <p>This, however, <a href="http://sqlfiddle.com/#!4/d41d8/34080">works</a>:</p> <pre><code>select 'A' as x from dual union all select 'B' as x from dual union all select 'C' from dual order by x asc </code></pre> <p>I've been playing around with this issue and figured out that apparently, at least the first subselect and the <em>second-last</em> (??) subselect need to have a column called <code>x</code>. In the first example, the two subselects seemed to simply coincide. <a href="http://sqlfiddle.com/#!4/d41d8/34081">Working example</a>:</p> <pre><code>select 'A' as x from dual union all select 'B' from dual union all select 'C' from dual union all select 'D' from dual union all select 'E' from dual union all select 'F' as x from dual union all select 'G' from dual order by x asc </code></pre> <p>As you may have guessed, this <a href="http://sqlfiddle.com/#!4/d41d8/34082">wouldn't work</a>:</p> <pre><code>select 'A' as x from dual union all select 'B' from dual union all select 'C' from dual union all select 'D' from dual union all select 'E' as x from dual union all select 'F' from dual union all select 'G' from dual order by x asc </code></pre> <h3>Interesting side-note:</h3> <p>Derived tables seem not to suffer from this limitation. <a href="http://sqlfiddle.com/#!4/d41d8/34123">This works</a>:</p> <pre><code>select * from ( select 'A' as x from dual union all select 'B' from dual union all select 'C' from dual ) order by x asc </code></pre> <h3>Question:</h3> <p>Is this a (known?) bug in the Oracle SQL parser, or is there any very subtle detail in the language syntax that absolutely requires the first and the second-last subselect to hold a column of the name as referenced from the <code>ORDER BY</code> clause?</p>
25,390,187
2
3
null
2014-08-19 15:58:37.99 UTC
4
2014-08-20 06:23:01.58 UTC
2014-08-20 06:23:01.58 UTC
null
521,799
null
521,799
null
1
31
sql|oracle|oracle11g|sql-order-by|union-all
8,166
<p>This doesn't really answer the question, but it seems to be a parser bug (or 'feature') rather than a language requirement.</p> <p>According to My Oracle Support, this seems to have been raised as bug 14196463 but closed with no resolution. It's also mentioned in <a href="https://community.oracle.com/thread/3561546" rel="noreferrer">community thread 3561546</a>. You need a MOS account, or at least an Oracle account, to see either of those though.</p> <p>It's also been discussed <a href="https://community.oracle.com/thread/2471511" rel="noreferrer">in an OTN thread</a> which requires a basic Oracle login rather than a MOS account, as far as I can tell. That also doesn't have much information but repeats your findings, and also suggests the behaviour has existed back at least to 9.2.0.8 and perhaps much earlier.</p> <p><a href="http://docs.oracle.com/cd/E11882_01/server.112/e41084/queries005.htm#SQLRF52348" rel="noreferrer">The documentation</a> is a bit vague but doesn't indicate this is expected to be a problem:</p> <blockquote> <p>For compound queries containing set operators <code>UNION</code>, <code>INTERSECT</code>, <code>MINUS</code>, or <code>UNION ALL</code>, the <code>ORDER BY</code> clause must specify positions or aliases rather than explicit expressions. Also, the <code>ORDER BY</code> clause can appear only in the last component query. The <code>ORDER BY</code> clause orders all rows returned by the entire compound query.</p> </blockquote> <p>You are aliasing your expression and using that, and it doesn't say you have to alias particular components (although of course it doesn't say you <em>don't</em> have to either).</p> <p>The behaviour seems inconsistent with the alias being valid for the final projection, and the usual rule about the alias only being valid in the order by clause - this seems to be falling down somewhere in between.</p>
48,550,955
MVC bootstrap navbar not working after running NuGet updates
<p>An MVC app broke after we updated all the NuGet packages. After trying everything I created a new MVC app, updated the NuGet packages and the basic navbar...</p> <pre><code>&lt;div class="navbar navbar-inverse navbar-fixed-top"&gt; &lt;div class="container"&gt; &lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;a class="navbar-brand" href="/"&gt;Application name&lt;/a&gt; &lt;/div&gt; &lt;div class="navbar-collapse collapse"&gt; &lt;ul class="nav navbar-nav"&gt; &lt;li&gt;&lt;a href="/"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/Home/About"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/Home/Contact"&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;ul class="nav navbar-nav navbar-right"&gt; &lt;li&gt;&lt;a href="/Account/Register" id="registerLink"&gt;Register&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/Account/Login" id="loginLink"&gt;Log in&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>... looks like this ...</p> <p><a href="https://i.stack.imgur.com/VkNu1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VkNu1.png" alt="NavBar"></a></p> <p>...and clicking the icon...</p> <p><a href="https://i.stack.imgur.com/flggT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/flggT.png" alt="NavBar Open"></a></p> <p>Any ideas what could be causing this?</p> <p>Have tried manually adding Bootstrap.css and Bootstrap.js to _Layout.vbhtml, but no difference</p> <p>Thank you</p>
48,630,895
15
6
null
2018-01-31 20:31:56.757 UTC
29
2021-06-21 08:09:20.003 UTC
2018-01-31 20:39:40.093 UTC
null
1,956,080
null
1,956,080
null
1
55
twitter-bootstrap|asp.net-mvc-5|nuget-package
39,977
<p>Finally, I managed my HTML and yours. There're a lot of changes in Bootstrap 4 in compare to version 3. Regarding your markup, you have to change:</p> <ol> <li>"Navbar-inverse" to "Navbar-dark" and use color "bg-dark".</li> <li>Add few attributes to button, as "aria-controls", "aria-expanded", "aria-label" and "data-target" for link to another element.</li> <li>Property "id" to collapsable element.</li> <li>For list elements (tag LI) should be added class="nav-item"</li> <li>For links unside list elements add class="nav-link".</li> <li>I suggest to add "mr-auto" to list definiton.</li> </ol> <p>All changes below. Tested <a href="https://codepen.io/anon/pen/xYOXGG/" rel="noreferrer">here</a>.</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-html lang-html prettyprint-override"><code>&lt;nav class="navbar navbar-expand-sm navbar-dark fixed-top bg-dark"&gt; &lt;div class="container"&gt; &lt;button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"&gt; &lt;/button&gt; &lt;a class="navbar-brand" href="/"&gt;Application name&lt;/a&gt; &lt;div class="navbar-collapse collapse" id="navbarSupportedContent"&gt; &lt;ul class="nav navbar-nav mr-auto"&gt; &lt;li class="nav-item"&gt;&lt;a href="/" class="nav-link"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li class="nav-item"&gt;&lt;a href="/Home/About" class="nav-link"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li class="nav-item"&gt;&lt;a href="/Home/Contact" class="nav-link"&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;ul class="nav navbar-nav navbar-right mr-auto"&gt; &lt;li class="nav-item"&gt;&lt;a href="/Account/Register" id="registerLink" class="nav-link"&gt;Register&lt;/a&gt;&lt;/li&gt; &lt;li class="nav-item"&gt;&lt;a href="/Account/Login" id="loginLink" class="nav-link"&gt;Log in&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/nav&gt;</code></pre> </div> </div> </p>
39,245,967
How to unselect options in select using jquery
<p>Below is my HTML. I have given multiple <code>option</code> elements in the <code>select</code> tag.</p> <pre><code>&lt;select class="car" multiple size="3"&gt; &lt;option value="volvo"&gt;Volvo&lt;/option&gt; &lt;option value="saab"&gt;Saab&lt;/option&gt; &lt;option value="opel"&gt;Opel&lt;/option&gt; &lt;option value="audi"&gt;Audi&lt;/option&gt; &lt;/select&gt; </code></pre> <p>I am able to multi-select by holding the <kbd>CTRL</kbd> key. I am able to retrieve the selected values using the following jQuery</p> <pre><code>$.each($(".car option:selected"), function() { countries.push($(this).val()); }); </code></pre> <p>How can I unselect the value using jQuery? The selected value will be highlighted as shown:</p> <p><a href="https://i.stack.imgur.com/ztTXi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ztTXi.png" alt="enter image description here"></a></p> <p>Thanks in advance</p>
39,246,137
2
4
null
2016-08-31 09:37:40.7 UTC
1
2022-02-24 18:10:23.637 UTC
2016-08-31 09:42:32.38 UTC
null
519,413
null
5,437,218
null
1
8
javascript|jquery|html
43,707
<p>Set the <code>selected</code> property to <code>false</code>: <code>$(selector).prop('selected', false)</code>.</p> <p>I have added a button and attached a click event to be able to demonstrate.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var countries = []; function unselect() { $.each($(".car option:selected"), function () { countries.push($(this).val()); $(this).prop('selected', false); // &lt;-- HERE }); } $("#unselect").click(unselect);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;select class="car" multiple size="3"&gt; &lt;option value="volvo"&gt;Volvo&lt;/option&gt; &lt;option value="saab"&gt;Saab&lt;/option&gt; &lt;option value="opel"&gt;Opel&lt;/option&gt; &lt;option value="audi"&gt;Audi&lt;/option&gt; &lt;/select&gt; &lt;input type="button" value="unselect" id="unselect" /&gt;</code></pre> </div> </div> </p>
26,829,295
Getting the coordinates from the location I touch the touchscreen
<p>I try to get the coordinates from the location where I hit the touchscreen to do put a specific UIImage at this point.</p> <p>How can I do this?</p>
26,829,360
6
1
null
2014-11-09 14:34:23.01 UTC
6
2019-07-18 09:22:13.157 UTC
2017-04-18 20:34:12.287 UTC
null
559,745
null
3,945,472
null
1
29
swift|coordinates|touchscreen
47,588
<p>In a <code>UIResponder</code> subclass, such as <code>UIView</code>:</p> <pre><code>override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { let touch = touches.anyObject()! as UITouch let location = touch.locationInView(self) } </code></pre> <p>This will return a <code>CGPoint</code> in view coordinates. </p> <p><strong>Updated with Swift 3 syntax</strong></p> <pre><code>override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { let touch = touches.first! let location = touch.location(in: self) } </code></pre> <p><strong>Updated with Swift 4 syntax</strong></p> <pre><code>override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) { let touch = touches.first! let location = touch.location(in: self.view) } </code></pre>
7,402,264
Primefaces onclick and onsuccess differences
<p>I have the following situation:</p> <p>after clicking a button, some business logic is done and after it is done, a new tab with a report should be visible.</p> <pre><code>&lt;p:commandButton value="this button" update="growlMain" actionListener="#{myBean.businesslogic}" onstart="ajaxDialog.show();" oncomplete="ajaxDialog.hide();" onsuccess="window.open('./report.jsp', '_newtab');" /&gt; </code></pre> <p>This does not work :(</p> <p>If the business logic only lasts some milliseconds, the following works:</p> <pre><code>&lt;p:commandButton value="this button" update="growlMain" actionListener="#{myBean.fastbusinesslogic}" onclick="window.open('./report.jsp', '_newtab');" /&gt; </code></pre> <p>the onclick opens a new tab, also things like onstart but it doesn't work with onsuccess or oncomplete. Why? And is there a solution for business logic that lasts some seconds?</p>
7,995,756
3
1
null
2011-09-13 12:59:33.843 UTC
9
2017-09-12 14:52:03.767 UTC
null
null
null
null
767,502
null
1
17
jsf|primefaces
58,927
<p>I have noticed that onsuccess for PrimeFaces command button does not work. The oncomplete however works and does the needful even if there is an error , such as in my case shows a success dialog even if there is an error in my business logic. Tried to use onsuccess but doesn't work. You could try oncomplete as below:</p> <pre><code>&lt;p:commandButton value="this button" update="growlMain" actionListener="#{myBean.businesslogic}" onstart="ajaxDialog.show();" oncomplete="ajaxDialog.hide(); window.open('./report.jsp', '_newtab');"/&gt; </code></pre>
7,054,708
Track events using Chrome javascript debugger
<p>I don't have a specific use case here, but occasionally I have been either helping out someone on SO or seen a cool javascript effect on a website and been curious about the code that drives it. However, the event that drives the code may not be immediately obvious. If I can't find the event handler then it can be really hard to find the js responsible for the effects I am interested in. Is there a quick way in the debugger to identify the events attached to an element and to drop a break point in when it fires?</p> <p>So for example an event may exist on a structure something like so </p> <pre><code>&lt;div&gt; &lt;ul&gt; &lt;li&gt;&lt;span&gt;&lt;img /&gt;&lt;/span&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>Now I don't know if the event is bound to the img, span, li, ul or div itself. Chrome has the Event Listeners area, but I feel like it doesn't always contain events. Anything you guys do that allows you to quickly find the event and drop a break point into it?</p>
7,054,733
3
0
null
2011-08-14 02:56:12.303 UTC
10
2015-08-25 19:59:20.267 UTC
null
null
null
null
510,314
null
1
33
javascript|debugging|google-chrome-devtools
39,557
<p>yes there is!</p> <p>find the element that is being reloaded and right click, choose inspect from context menu, then right click the html of the element (in the bottom firebugish pane), in the context menu there are options to:</p> <ul> <li>break on subtree modifications </li> <li>break on attributes modifications</li> <li>break on node removal</li> </ul> <p>Article on awesome new dev features in chrome: <a href="http://elijahmanor.com/7-chrome-tips-developers-designers-may-not-know/" rel="noreferrer">http://elijahmanor.com/7-chrome-tips-developers-designers-may-not-know/</a></p>
7,342,084
jQuery/Javascript - How to wait for manipulated DOM to update before proceeding with function
<p>What I'm trying to do is to update a simple div to say "Processing..." before executing a CPU-intensive script (it takes 3-12 seconds to run, no AJAX) then update the div to say "Finished!" when done. </p> <p>What I'm seeing is the div never gets updated with "Processing...". If I set a breakpoint immediately after that command, then the div text does get updated, so I know the syntax is correct. Same behavior in IE9, FF6, Chrome13.</p> <p>Even when bypassing jQuery and using basic raw Javascript, I see the same issue.</p> <p>You'd think this would have an easy answer. However, since the jQuery .html() and .text() don't have a callback hook, that's not an option. It's also not animated, so there is no .queue to manipulate.</p> <p>You can test this yourselves using the sample code I prepared below that shows both the jQuery and Javascript implementations with a 5 second high-CPU function. The code is easy to follow. When you click either the button or the link, you never see "Processing..."</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" &gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; function addSecs(d, s) {return new Date(d.valueOf()+s*1000);} function doRun() { document.getElementById('msg').innerHTML = 'Processing JS...'; start = new Date(); end = addSecs(start,5); do {start = new Date();} while (end-start &gt; 0); document.getElementById('msg').innerHTML = 'Finished JS'; } $(function() { $('button').click(function(){ $('div').text('Processing JQ...'); start = new Date(); end = addSecs(start,5); do {start = new Date();} while (end-start &gt; 0); $('div').text('Finished JQ'); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="msg"&gt;Not Started&lt;/div&gt; &lt;button&gt;jQuery&lt;/button&gt; &lt;a href="#" onclick="doRun()"&gt;javascript&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
7,342,127
4
3
null
2011-09-08 01:01:27.263 UTC
6
2019-08-26 13:58:44.233 UTC
2012-07-30 12:36:26.407 UTC
null
250,259
null
933,802
null
1
35
javascript|jquery|dom|high-load
32,636
<p>set it to processing, then do a setTimeout to prevent the cpu intensive task from running until after the div has been updated.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" &gt;&lt;/script&gt; &lt;script&gt; function addSecs(d, s) {return new Date(d.valueOf()+s*1000);} function doRun() { document.getElementById('msg').innerHTML = 'Processing JS...'; setTimeout(function(){ start = new Date(); end = addSecs(start,5); do {start = new Date();} while (end-start &gt; 0); document.getElementById('msg').innerHTML = 'Finished Processing'; },10); } $(function() { $('button').click(doRun); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="msg"&gt;Not Started&lt;/div&gt; &lt;button&gt;jQuery&lt;/button&gt; &lt;a href="#" onclick="doRun()"&gt;javascript&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>you can modify the setTimeout delay as needed, it may need to be larger for slower machines/browsers.</p> <p>Edit:</p> <p>You could also use an alert or a confirm dialog to allow the page time to update.</p> <pre><code>document.getElementById('msg').innerHTML = 'Processing JS...'; if ( confirm( "This task may take several seconds. Do you wish to continue?" ) ) { // run code here } </code></pre>
1,728,978
Recommendations (and Differences) between different Ruby on Rails Production Web Servers
<p>Very soon I plan on deploying my first Ruby on Rails application to a production environment and I've even picked a webhost with all the managed server and Capistrano goodness you'd expect from a RoR provider.</p> <p>The provider allows for Mongrel, Thin, Passenger &amp; FastCGI web servers, which seems very flexible, but I honestly don't know the differences between them. I have looked into them some, but it all gets a bit much when they start talking about features and maximum simultaneous requests - and that this data seems to vary depending on who's publishing it.</p> <p>I have looked at Passenger (on the surface) - which does seem very appealing to me - but I was under the impression that Passenger wasn't the actual webserver, and instead was more like a layer on top of Apache or nginx and managed spawned instances of the application (like a Mongrel cluster).</p> <p>Can anyone please set me straight with the differences in layman's terms so as I can choose wisely (because anyone who's seen <em>Indiana Jones and the Last Crusade</em> knows what happens if you choose poorly). </p>
1,729,055
4
1
null
2009-11-13 12:37:13.16 UTC
12
2019-05-08 13:06:37.19 UTC
2009-11-13 14:27:36.763 UTC
null
1,450
null
11,194
null
1
16
ruby-on-rails|webserver|passenger|fastcgi|mongrel
6,241
<p><strong>Short answer</strong></p> <p>Go with Apache/Nginx + Passenger. Passenger <a href="http://www.modrails.com/documentation.html" rel="nofollow noreferrer">is fast</a>, reliable, easy to configure and deploy. Passenger has been adopted by a large number of big Rails applications, including <a href="http://www.shopify.com/" rel="nofollow noreferrer">Shopify</a>.</p> <p><a href="https://i.stack.imgur.com/4o3lS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4o3lS.png" alt="alt text"></a><br> <sub>(source: <a href="http://www.modrails.com/images/passenger_mongrel_thin_benchmark.png" rel="nofollow noreferrer">modrails.com</a>)</sub> </p> <p><strong>The long answer</strong></p> <p>Forget about CGI and FastCGI. In the beginning there were no other alternatives so the only way to run Rails was using CGI or the faster browser FastCGI. Nowadays almost nobody runs Rails under CGI. The latest Rails versions no longer provides .cgi and .fcgi runners.</p> <p>Mongrel has been a largely adopted solution, the best replacement for CGI and FCGI. Many sites still use Mongrel and Mongrel cluster, however Mongrel project is almost dead and many projects already moved to other solutions (mostly Passenger). Also, a Mongrel based architecture is quite hard to configure because it needs a frontend proxy (thin, ngnix) and a backend architecture composed of multiple Mongrel instances.</p> <p>Passenger has been gaining widespread attention since it was released. Many projects switched from Mongrel to Passenger for many reasons, including (but not limited to) easy deployment, maintainability and performance. Additionally, Passenger is now available for both Apache and Ngnix.</p> <p>The simplest way to use Passenger is the Apache + Passenger configuration. One Apache installation and multiple Passenger processes.</p> <p>If you need better performance and scalability, you can use Ngnix as a frontend proxy and forward all Rails requests to multiple backend servers, each one composed of Apache + Passenger. I'm not going into the technical details here, this solution is intended to be used by Rails projects with an high level of traffic.</p> <p>Even more complex solutions include a combination of different levels including http proxies and servers. You can have an idea of what I'm talking about reading some internal details from <a href="http://github.com/blog/517-unicorn" rel="nofollow noreferrer">GitHub</a> and <a href="http://heroku.com/how/architecture" rel="nofollow noreferrer">Heroku</a>.</p> <p>Right now, Passenger is the best answer for most Rails projects.</p>
10,399,614
Accessing value inside nested dictionaries
<p>I am new to python and need help in solving an issue:</p> <p>I have a dictionary like </p> <pre><code>tmpDict = {'ONE':{'TWO':{'THREE':10}}} </code></pre> <p>Do we have any other way to access THREE's value other than doing </p> <pre><code>tmpDict['ONE']['TWO']['THREE'] </code></pre> <p>?</p>
10,399,718
5
2
null
2012-05-01 15:03:20.25 UTC
12
2018-08-24 09:23:09.73 UTC
2017-10-30 06:29:46.48 UTC
null
4,099,593
null
1,076,582
null
1
43
python|dictionary
145,178
<p>You can use the get() on each dict. Make sure that you have added the None check for each access. </p>
10,355,411
IE10 - CSS animation not working
<p>I have a scale animation that worked in IE10 for about a day and then stopped. I didn't make any changes and am not sure what would happen to break it. </p> <p>Does anyone have any ideas? When I look in the IE dev tools it's not picking up the animation name, but is picking up all the other properties.</p> <p>Here's the CSS:</p> <pre><code>@-ms-keyframes move97 { 0% { transform:scale(1,1); -ms-transform:scale(1,1); -moz-transform:scale(1,1); -webkit-transform:scale(1,1); -o-transform:scale(1,1); } 50% { transform:scale(0.97,0.97); -ms-transform:scale(0.97,0.97); -moz-transform:scale(0.97,0.97); -webkit-transform:scale(0.97,0.97); -o-transform:scale(0.97,0.97); } 100% { transform:scale(1,1); -ms-transform:scale(1,1); -moz-transform:scale(1,1); -webkit-transform:scale(1,1); -o-transform:scale(1,1); } } .press97 { -ms-animation-name: move97 0.2s; /* note MS has this different.... ugh */ animation: move97 0.2s; -moz-animation: move97 0.2s; /* Firefox */ -webkit-animation: move97 0.2s; /* Safari and Chrome */ animation-timing-function: linear; -moz-animation-timing-function: linear; -webkit-animation-timing-function: linear; -ms-animation-timing-function: linear; animation-fill-mode: forwards; -webkit-animation-fill-mode: forwards; -moz-animation-fill-mode: forwards; -ms-animation-fill-mode: forwards; } </code></pre>
10,358,822
2
3
null
2012-04-27 17:46:06.943 UTC
null
2020-12-30 14:19:51.003 UTC
2012-06-04 14:01:57.173 UTC
null
54,680
null
389,809
null
1
6
animation|css|internet-explorer-10
53,506
<p>Apparently the help link I was following isn't correct. When I change it to -ms-animation: move97 0.2s, it works. This is what I had originally and it did NOT work, so I changed it to what's shown above, which did. </p> <p>Help link I followed: <a href="http://msdn.microsoft.com/library/ie/hh673530.aspx" rel="noreferrer">http://msdn.microsoft.com/library/ie/hh673530.aspx</a></p> <p>I've been told it'll be corrected.</p>
7,433,575
Cannot create a session after the response has been committed
<p>Opening the JSF page gives me the following exception:</p> <blockquote> <p>Caused by: java.lang.IllegalStateException: Cannot create a session after the response has been committed</p> </blockquote> <p>Here is the JSF code:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.prime.com.tr/ui"&gt; &lt;h:head&gt; &lt;h:outputStylesheet name="master_c.css" library="css" /&gt; &lt;title&gt;Quotes&lt;/title&gt; &lt;/h:head&gt; &lt;h:body styleClass="venue product"&gt; &lt;h:form&gt; &lt;div id="wrapper"&gt; &lt;div id="content"&gt; &lt;h2&gt;&lt;a href="#"&gt;&lt;img src="/Webify/static/image/venue-large.png" /&gt;&lt;/a&gt;&lt;/h2&gt; &lt;ul id="calltoaction"&gt; &lt;li id="cta-map"&gt;&lt;a href="#"&gt;MAP&lt;/a&gt;&lt;/li&gt; &lt;li id="cta-download" class="addthis_toolbox addthis_share_btn"&gt;&lt;a href="#"&gt;qmobile&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;!-- calltoaction --&gt; &lt;div class="sec-content"&gt; &lt;ul id="techspecs" class="mobile"&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;img height="50" width="79" alt="QMobile Kâşif" src="/Webify/static/image/mac-universal.png" /&gt;&lt;b&gt;QMobile&lt;/b&gt;&lt;br /&gt;Bahara&lt;br /&gt;Pahli baar&lt;/li&gt; &lt;li&gt;Lorem Ispum Lorem Ispum Lorem Ispum Lorem Ispum Lorem Ispum Lorem Ispum Lorem Ispum Lorem Ispum Lorem Ispum Lorem Ispum Lorem Ispum Lorem Ispum&lt;/li&gt; &lt;/ul&gt; &lt;!-- techspecs --&gt; &lt;ul id="sc-reviews" class="mobile"&gt; &lt;li&gt;&lt;a href="#"&gt;&lt;img height="35" width="200" alt="Android" src="/Webify/static/image/text_android.png" /&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;&lt;img height="35" width="200" alt="IPhone" src="/Webify/static/image/text_iphone.png" /&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;&lt;img height="35" width="200" alt="BlackBerry" src="/Webify/static/image/text_blackberry.png" /&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Find More...&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;!-- sc-reviews --&gt; &lt;/div&gt; &lt;div class="prim-content"&gt; &lt;!-- Page Heading --&gt; &lt;div id="sec-navigation"&gt; &lt;h3 style="margin-left: 10px;"&gt;&lt;/h3&gt; &lt;/div&gt; &lt;div id="wall"&gt; &lt;!-- bricks end --&gt; &lt;/div&gt; &lt;!-- wall end --&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/h:form&gt; &lt;/h:body&gt; &lt;/html&gt; </code></pre> <p>Here is the stacktrace:</p> <pre><code>Sep 16, 2011 1:45:40 PM com.sun.faces.application.view.FaceletViewHandlingStrategy handleRenderException SEVERE: Error Rendering View[/streamfaces.xhtml] java.lang.IllegalStateException: Cannot create a session after the response has been committed at org.apache.catalina.connector.Request.doGetSession(Request.java:2734) at org.apache.catalina.connector.Request.getSession(Request.java:2244) at org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:899) at com.sun.faces.context.ExternalContextImpl.getSession(ExternalContextImpl.java:155) at com.sun.faces.renderkit.ServerSideStateHelper.writeState(ServerSideStateHelper.java:175) at com.sun.faces.renderkit.ResponseStateManagerImpl.writeState(ResponseStateManagerImpl.java:122) at com.sun.faces.application.StateManagerImpl.writeState(StateManagerImpl.java:166) at com.sun.faces.application.view.WriteBehindStateWriter.flushToWriter(WriteBehindStateWriter.java:225) at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:418) at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131) at com.ocpsoft.pretty.faces.application.PrettyViewHandler.renderView(PrettyViewHandler.java:163) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:399) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:317) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:204) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:182) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:311) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619) Sep 16, 2011 1:45:40 PM com.sun.faces.context.ExceptionHandlerImpl throwIt INFO: Exception when handling error trying to reset the response. java.lang.IllegalStateException: Cannot create a session after the response has been committed at org.apache.catalina.connector.Request.doGetSession(Request.java:2734) at org.apache.catalina.connector.Request.getSession(Request.java:2244) at org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:899) at com.sun.faces.context.ExternalContextImpl.getSession(ExternalContextImpl.java:155) at com.sun.faces.renderkit.ServerSideStateHelper.writeState(ServerSideStateHelper.java:175) at com.sun.faces.renderkit.ResponseStateManagerImpl.writeState(ResponseStateManagerImpl.java:122) at com.sun.faces.application.StateManagerImpl.writeState(StateManagerImpl.java:166) at com.sun.faces.application.view.WriteBehindStateWriter.flushToWriter(WriteBehindStateWriter.java:225) at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:418) at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131) at com.ocpsoft.pretty.faces.application.PrettyViewHandler.renderView(PrettyViewHandler.java:163) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:399) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:317) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:204) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:182) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:311) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619) Sep 16, 2011 1:45:40 PM com.sun.faces.renderkit.RenderKitUtils renderHtmlErrorPage WARNING: JSF1087: Unable to generate Facelets error page as the response has already been committed. Sep 16, 2011 1:45:40 PM com.sun.faces.renderkit.RenderKitUtils renderHtmlErrorPage SEVERE: javax.faces.FacesException: Cannot create a session after the response has been committed javax.faces.FacesException: Cannot create a session after the response has been committed at com.sun.faces.context.ExceptionHandlerImpl.handle(ExceptionHandlerImpl.java:141) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:119) at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:399) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:317) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:204) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:182) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:311) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619) Caused by: java.lang.IllegalStateException: Cannot create a session after the response has been committed at org.apache.catalina.connector.Request.doGetSession(Request.java:2734) at org.apache.catalina.connector.Request.getSession(Request.java:2244) at org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:899) at com.sun.faces.context.ExternalContextImpl.getSession(ExternalContextImpl.java:155) at com.sun.faces.renderkit.ServerSideStateHelper.writeState(ServerSideStateHelper.java:175) at com.sun.faces.renderkit.ResponseStateManagerImpl.writeState(ResponseStateManagerImpl.java:122) at com.sun.faces.application.StateManagerImpl.writeState(StateManagerImpl.java:166) at com.sun.faces.application.view.WriteBehindStateWriter.flushToWriter(WriteBehindStateWriter.java:225) at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:418) at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131) at com.ocpsoft.pretty.faces.application.PrettyViewHandler.renderView(PrettyViewHandler.java:163) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) ... 19 more </code></pre> <p>How is this problem caused and how can I solve it? I am using Mojarra 2.1.2. </p>
7,619,888
5
1
null
2011-09-15 15:40:02.417 UTC
5
2022-07-30 12:26:29.837 UTC
2011-09-17 04:17:05.59 UTC
null
157,882
null
811,750
null
1
18
jsf|mojarra
69,797
<p>[SOLVED]</p> <p>It took days to diagnose this problem, but finally I am able to solve this problem. </p> <p>It was actually <code>@ViewScoped</code> and it has a managed property DAO object which was not serialized. So after view is rendered, facelets also produce this exception, but JSF view already rendered and that's why this exception showed. </p> <p><strong>Solution:</strong> Make all objects serialized in <code>@ViewScoped</code> bean, and mark "transient" who are not serialized like in my case it was DAO object in JSF <code>@ViewScoped</code>.</p>
7,058,507
Fixed aspect ratio View
<p>How would I go implementing a fixed aspect ratio <code>View</code>? I'd like to have items with 1:1 aspect ratio in a <code>GridView</code>. I think it's better to subclass the children than the <code>GridView</code>?</p> <p>EDIT: I assume this needs to be done programmatically, that's no problem. Also, I don't want to limit the size, only the aspect ratio.</p>
10,772,572
10
4
null
2011-08-14 17:34:38.537 UTC
22
2022-05-24 06:31:50.85 UTC
2016-07-19 00:17:04.49 UTC
null
1,318,479
null
706,690
null
1
51
android|view|aspect-ratio|viewgroup
55,931
<p>I implemented FixedAspectRatioFrameLayout, so I can reuse it and have any hosted view be with fixed aspect ratio:</p> <pre><code>public class FixedAspectRatioFrameLayout extends FrameLayout { private int mAspectRatioWidth; private int mAspectRatioHeight; public FixedAspectRatioFrameLayout(Context context) { super(context); } public FixedAspectRatioFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public FixedAspectRatioFrameLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context, attrs); } private void init(Context context, AttributeSet attrs) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FixedAspectRatioFrameLayout); mAspectRatioWidth = a.getInt(R.styleable.FixedAspectRatioFrameLayout_aspectRatioWidth, 4); mAspectRatioHeight = a.getInt(R.styleable.FixedAspectRatioFrameLayout_aspectRatioHeight, 3); a.recycle(); } // **overrides** @Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) { int originalWidth = MeasureSpec.getSize(widthMeasureSpec); int originalHeight = MeasureSpec.getSize(heightMeasureSpec); int calculatedHeight = originalWidth * mAspectRatioHeight / mAspectRatioWidth; int finalWidth, finalHeight; if (calculatedHeight &gt; originalHeight) { finalWidth = originalHeight * mAspectRatioWidth / mAspectRatioHeight; finalHeight = originalHeight; } else { finalWidth = originalWidth; finalHeight = calculatedHeight; } super.onMeasure( MeasureSpec.makeMeasureSpec(finalWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(finalHeight, MeasureSpec.EXACTLY)); } } </code></pre>
7,665,540
TCPDF ERROR: [Image] Unable to get image
<p>I'm using <strong>TCPDF</strong> with Drupal's <em>print</em> module to generate PDF of articles, &amp; ending up with following error message when I click the link to generate PDF:</p> <p><code>TCPDF ERROR: [Image] Unable to get image: http://localhost/pathToDrupal/themes/bartik/logo.png</code></p> <p>The Image exists in the location specified. I tried applying:</p> <pre><code>allow_url_fopen = On; allow_url_include = On; </code></pre> <p>in <code>php.ini</code> but that could not resolve the problem. </p> <p>Please care to help :(</p>
7,665,966
13
0
null
2011-10-05 17:57:26.427 UTC
4
2019-08-18 10:15:29.423 UTC
null
null
null
null
493,329
null
1
25
php|tcpdf
86,878
<p>Apparently the "fopen"-wrappers are not used by TCPDF.</p> <p>If you supply the URL of an image, TCPDF tries to download it with cURL into the "cache"-directory where your TCPDF-installation is stored (you have to check what the <code>K_PATH_CACHE</code>-constant contains to be sure). </p> <p>So I guess you have to have write permissions in this directory that the magic works. Also you need cURL enabled.</p>
13,994,507
How do you send a custom header in a CORS preflight OPTIONS request?
<p>I am trying to send a CORS request for a JSON payload. I control both the server and the client.</p> <p>I'm following along here: <a href="https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS?redirectlocale=en-US&amp;redirectslug=HTTP_access_control" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS?redirectlocale=en-US&amp;redirectslug=HTTP_access_control</a></p> <p>The server has a custom header that must be sent along with every request. This custom header therefore makes the request 'not simple' and thus the request must be preflighted with an OPTIONS request.</p> <p>I can see jQuery making the OPTIONS request, but it doesn't send the custom header along.</p> <p>Methods I've tried:</p> <ul> <li>Using the beforeSend option: <a href="http://api.jquery.com/jQuery.ajax/" rel="nofollow noreferrer">http://api.jquery.com/jQuery.ajax/</a></li> <li>Using an AJAX prefilter: <a href="http://api.jquery.com/jQuery.ajaxPrefilter/" rel="nofollow noreferrer">http://api.jquery.com/jQuery.ajaxPrefilter/</a></li> </ul> <p>In both cases, the browser is not sending the custom header along.</p> <p>I'm using FF 17.0.1, jQuery 1.8.3.</p>
13,997,235
1
4
null
2012-12-21 17:22:46.97 UTC
9
2022-07-18 01:19:39.09 UTC
2022-07-18 01:19:39.09 UTC
null
1,161,484
null
203,619
null
1
32
jquery|cors|xmlhttprequest
44,403
<p>Your problem isn't with jquery, it's in <a href="http://www.w3.org/TR/cors/" rel="noreferrer">how CORS works</a>. Your beforeSend callback was probably working as expected... but browsers won't send custom headers in preflight requests, no matter what. This is by design; the purpose of the preflight request is to determine what information the useragent (browser) is permitted to send beyond the "simple" stuff defined in the CORS spec. Thus, for the useragent to send any non-simple data (such as your custom header) as part of the preflight request is self-defeating.</p> <p>To instruct the useragent to include your custom header in the actual CORS request, include a <a href="http://www.w3.org/TR/cors/#access-control-request-headers-request-header" rel="noreferrer"><code>Access-Control-Allow-Headers</code> header</a> in your preflight response. It's worth noting that if you're not overly concerned with what headers the useragent transmits, I believe you can just echo back the value of the <code>Access-Control-Request-Headers</code> request header field as the value of the <code>Access-Control-Allow-Headers</code> you send in the response.</p> <p>You may also want to include some of the other <code>Access-Control-Allow-*</code> headers defined in the <a href="http://www.w3.org/TR/cors/#syntax" rel="noreferrer">syntax section of the spec</a>.</p> <p>See also <a href="https://stackoverflow.com/questions/8685678/cors-how-do-preflight-an-httprequest">CORS - How do &#39;preflight&#39; an httprequest?</a></p> <p>See also <a href="https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Preflighted_requests" rel="noreferrer">Mozilla's CORS preflight example</a>, which shows these headers in action.</p>
14,245,692
Are *.tlb files ever used at runtime?
<p>I'm working on a product that exposes some .NET API through COM interop. As a part of the build we generate *.tlb files for all such assemblies and deliver them as a part of a separate SDK package. Our customers can install the SDK on top of our product and create applications that use our COM API.</p> <p>Do we need to ship and register those *.tlb files with the product itself? Is there a situation when *.tlb are required at runtime, when third-party libraries coded against them are executed? </p> <p>Please explain how it works, if you answer Yes. I seen a lot of comments all over the internet that say that I have to deliver and register them, but I did not find one that clearly explains why it should be done. That made me doubt that it is true.</p>
14,246,694
2
0
null
2013-01-09 20:16:47.393 UTC
6
2021-08-12 19:01:14.75 UTC
2013-01-09 20:45:26.96 UTC
null
176,848
null
176,848
null
1
40
.net|com
18,842
<p>Yes, that's possible. Especially in the case of .NET, you should not omit registering the type library because you cannot predict how the client code is going to use your server.</p> <p>They are not particularly common but there are two cases:</p> <ul> <li><p>When the client code calls your [ComVisible] method and the call crosses an apartment boundary. Apartments are a COM concept that is a bit fuzzy, you have to understand the difference between STA and MTA threads. Keeping it simple: an apartment boundary is typically crossed when the call is made from another thread, from another process or from another machine. COM needs help to figure out how to serialize the arguments of the call into a IPC packet and that requires knowing the type of the arguments. There is no concept of Reflection in COM so it cannot easily be done automatically. A separate DLL is required that implements the proxy and the stub, almost always generated from an IDL file. That's hard to come by in .NET, you almost always use the convenient second way, using the standard marshaller built into Windows. Which uses a type library to find out what the argument types are. The Regasm.exe /tlb option ensures that the interface proxy/stub and type library is registered so the standard marshaller can find the library.</p> </li> <li><p>When you expose a struct in your public interface. Structs are very troublesome in interop scenarios, they have a layout that's highly dependent on compiler settings. The equivalent .NET property is StructLayout.Pack. Fixed at 8 in .NET but the client code doesn't know that. To access a struct, the client code must use IRecordInfo. Which lets it find out where every field of the struct is located in memory. A type library provides the info that IRecordInfo needs. It is certainly best to avoid structs entirely and very easily done in .NET.</p> </li> </ul>
13,932,946
Transparent text cut out of background
<p>Is there any way to make a <strong>transparent text cut out of a background</strong> effect like the one in the following image, with CSS?<br> It would be sad to lose all precious SEO because of images replacing text.</p> <p><img src="https://i.stack.imgur.com/V6Bu7.png" alt="Transparent text cut out of background"></p> <p>I first thought of shadows but I can't figure anything out... </p> <p>The image is the site background, an absolute positioned <code>&lt;img&gt;</code> tag </p>
13,933,418
14
6
null
2012-12-18 12:24:09.253 UTC
47
2022-05-31 03:37:10.49 UTC
2016-01-22 10:44:47.163 UTC
null
1,811,992
null
853,990
null
1
103
css|svg|fonts|css-shapes
102,729
<p>It's possible with css3 but it's not supported in all browsers</p> <p>With background-clip: text; you can use a background for the text, but you will have to align it with the background of the page</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background: url(http://www.color-hex.com/palettes/26323.png) repeat; margin:10px; } h1 { background-color:#fff; overflow:hidden; display:inline-block; padding:10px; font-weight:bold; font-family:arial; color:transparent; font-size:200px; } span { background: url(http://www.color-hex.com/palettes/26323.png) -20px -20px repeat; -webkit-text-fill-color: transparent; -webkit-background-clip: text; display:block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;h1&gt;&lt;span&gt;ABCDEFGHIKJ&lt;/span&gt;&lt;/h1&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/JGPuZ/1337/" rel="noreferrer">http://jsfiddle.net/JGPuZ/1337/</a></p> <hr /> <h2>Automatic Alignment</h2> <p>With a little javascript you can align the background automatically:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function(){ //Position of the header in the webpage var position = $("h1").position(); var padding = 10; //Padding set to the header var left = position.left + padding; var top = position.top + padding; $("h1").find("span").css("background-position","-"+left+"px -"+top+"px"); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background: url(http://www.color-hex.com/palettes/26323.png) repeat; margin:10px; } h1 { background-color:#fff; overflow:hidden; display:inline-block; padding:10px; font-weight:bold; font-family:arial; color:transparent; font-size:200px; } span { background: url(http://www.color-hex.com/palettes/26323.png) -20px -20px repeat; -webkit-text-fill-color: transparent; -webkit-background-clip: text; display:block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;h1&gt;&lt;span&gt;ABCDEFGHIKJ&lt;/span&gt;&lt;/h1&gt;</code></pre> </div> </div> ​</p> <p><a href="http://jsfiddle.net/JGPuZ/1336/" rel="noreferrer">http://jsfiddle.net/JGPuZ/1336/</a></p>
69,975,792
Error: [Home] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>
<p>Hello fellow friends I am trying to create my own app but facing issues after updating the react-router-dom to 6.02 I am getting this error</p> <blockquote> <p>Error: [Home] is not a Route component. All component children of Routes must be a Route or &lt;React.Fragment&gt;</p> </blockquote> <p>the code is the following</p> <pre><code>import { BrowserRouter, Route, Routes } from &quot;react-router-dom&quot;; import Navbar from &quot;./components/Navbar/Navbar&quot;; import Home from &quot;./pages/home/Home&quot;; import Login from &quot;./pages/login/Login&quot;; import Signup from &quot;./pages/signup/Signup&quot;; function App() { return ( &lt;div className=&quot;App&quot;&gt; &lt;BrowserRouter&gt; &lt;Navbar /&gt; &lt;Routes&gt; &lt;Route exact path=&quot;/&quot;&gt; &lt;Home /&gt; &lt;/Route&gt; &lt;Route path=&quot;/login&quot;&gt; &lt;Login /&gt; &lt;/Route&gt; &lt;Route path=&quot;/signup&quot;&gt; &lt;Signup /&gt; &lt;/Route&gt; &lt;/Routes&gt; &lt;/BrowserRouter&gt; &lt;/div&gt; ); } export default App; </code></pre>
69,975,860
6
7
null
2021-11-15 14:13:48.927 UTC
6
2022-04-01 11:28:50.11 UTC
null
null
null
null
15,721,007
null
1
31
reactjs
33,701
<p><code>&lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt; </code></p> <p><a href="https://reactrouter.com/docs/en/v6/upgrading/v5" rel="noreferrer">Migrating to v6</a></p>
30,170,400
which(vector1 < vector2)
<p>Let's make a small example first, that computes in R:</p> <pre><code>x&lt;- c(1,3,1,4,2) max(which(x&lt;2)) [1] 3 </code></pre> <p>Now, I would like to do this not just for one value 2, but for many values simultaneously. It should give me something like that:</p> <pre><code>max(which(x&lt;c(1,2,3,4,5,6))) [1] NA 3 5 5 5 5 </code></pre> <p>Of course I could run a <code>for</code> loop, but that is very slow:</p> <pre><code>for(i in c(1,2,3,4,5,6)){ test[i]&lt;-max(which(x&lt;i)) } </code></pre> <p>Is there a fast way to do this?</p>
30,171,117
5
6
null
2015-05-11 14:30:44.053 UTC
3
2021-01-20 15:31:58.687 UTC
2021-01-20 15:31:58.687 UTC
null
4,032,703
null
4,887,688
null
1
31
r|max|simultaneous
1,418
<p>Find the max index of each value seen in <code>x</code>:</p> <pre><code>xvals &lt;- unique(x) xmaxindx &lt;- length(x) - match(xvals,rev(x)) + 1L </code></pre> <p>Rearrange</p> <pre><code>xvals &lt;- xvals[order(xmaxindx,decreasing=TRUE)] xmaxindx &lt;- xmaxindx[order(xmaxindx,decreasing=TRUE)] # 2 4 1 3 # 5 4 3 2 </code></pre> <p>Select from those:</p> <pre><code>xmaxindx[vapply(1:6,function(z){ ok &lt;- xvals &lt; z if(length(ok)) which(ok)[1] else NA_integer_ },integer(1))] # &lt;NA&gt; 1 2 2 2 2 # NA 3 5 5 5 5 </code></pre> <p>It handily reports the values (in the first row) along with the indices (second row).</p> <hr> <p>The <code>sapply</code> way is simpler and probably not slower:</p> <pre><code>xmaxindx[sapply(1:6,function(z) which(xvals &lt; z)[1])] </code></pre> <hr> <p><strong>Benchmarks.</strong> The OP's case is not fully described, but here are some benchmarks anyway:</p> <pre><code># setup nicola &lt;- function() max.col(outer(y,x,"&gt;"),ties.method="last")*NA^(y&lt;=min(x)) frank &lt;- function(){ xvals &lt;- unique(x) xmaxindx &lt;- length(x) - match(xvals,rev(x)) + 1L xvals &lt;- xvals[order(xmaxindx,decreasing=TRUE)] xmaxindx &lt;- xmaxindx[order(xmaxindx,decreasing=TRUE)] xmaxindx[vapply(y,function(z){ ok &lt;- xvals &lt; z if(length(ok)) which(ok)[1] else NA_integer_ },integer(1))] } beauvel &lt;- function() Vectorize(function(u) ifelse(length(which(x&lt;u))==0,NA,max(which(x&lt;u))))(y) davida &lt;- function() vapply(y, function(i) c(max(which(x &lt; i)),NA)[1], double(1)) hallo &lt;- function(){ test &lt;- vector("integer",length(y)) for(i in y){ test[i]&lt;-max(which(x&lt;i)) } test } josho &lt;- function(){ xo &lt;- sort(unique(x)) xi &lt;- cummax(1L + length(x) - match(xo, rev(x))) xi[cut(y, c(xo, Inf))] } require(microbenchmark) </code></pre> <p>(@MrHallo's and @DavidArenburg's throw a bunch of warnings the way I have them written now, but that could be fixed.) Here are some results:</p> <pre><code>&gt; x &lt;- sample(1:4,1e6,replace=TRUE) &gt; y &lt;- 1:6 &gt; microbenchmark(nicola(),frank(),beauvel(),davida(),hallo(),josho(),times=10) Unit: milliseconds expr min lq mean median uq max neval nicola() 76.17992 78.01171 99.75596 98.43919 120.81776 127.63058 10 frank() 25.27245 25.44666 36.41508 28.44055 45.32306 73.66652 10 beauvel() 47.70081 59.47828 67.44918 68.93808 74.12869 95.20936 10 davida() 26.52582 26.55827 33.93855 30.00990 35.55436 57.24119 10 hallo() 26.58186 26.63984 32.68850 28.68163 33.54364 50.49190 10 josho() 25.69634 26.28724 37.95341 30.50828 47.90526 68.30376 10 There were 20 warnings (use warnings() to see them) &gt; &gt; &gt; x &lt;- sample(1:80,1e6,replace=TRUE) &gt; y &lt;- 1:60 &gt; microbenchmark(nicola(),frank(),beauvel(),davida(),hallo(),josho(),times=10) Unit: milliseconds expr min lq mean median uq max neval nicola() 2341.96795 2395.68816 2446.60612 2481.14602 2496.77128 2504.8117 10 frank() 25.67026 25.81119 42.80353 30.41979 53.19950 123.7467 10 beauvel() 665.26904 686.63822 728.48755 734.04857 753.69499 784.7280 10 davida() 326.79072 359.22803 390.66077 397.50163 420.66266 456.8318 10 hallo() 330.10586 349.40995 380.33538 389.71356 397.76407 443.0808 10 josho() 26.06863 30.76836 35.04775 31.05701 38.84259 57.3946 10 There were 20 warnings (use warnings() to see them) &gt; &gt; &gt; x &lt;- sample(sample(1e5,1e1),1e6,replace=TRUE) &gt; y &lt;- sample(1e5,1e4) &gt; microbenchmark(frank(),josho(),times=10) Unit: milliseconds expr min lq mean median uq max neval frank() 69.41371 74.53816 94.41251 89.53743 107.6402 134.01839 10 josho() 35.70584 37.37200 56.42519 54.13120 63.3452 90.42475 10 </code></pre> <p>Of course, comparisons might come out differently for the OP's true case.</p>
19,821,426
"New" Excel.Application vs Excel.Application
<p>I am seeking clarification on the impact of "New" on the objects and the script.</p> <p>My understanding is that if I need to perform actions on an excel document and the application is closed then I should use New Excel.Application.</p> <p>If I keep this application active (through an object such as a Workbook for example) and later in the script I decide to open another workbook, should I still use New Excel.Application or would it be better to use Excel.Application then?</p> <p>My concern lies in the fact that I am going to write a long script that will perform actions on at least 5 Workbooks. I will have to a switch from one Workbook to another and then come back to the former...</p> <p>If each time the script creates a New Excel.Application, I may end up having quite a lot of them running and I am fearing that this mess would generate issues.</p> <p>Is it more appropriate to write something like:</p> <pre><code>Dim NxlApp as New Excel.Application Dim xlApp as Excel.Application NxlApp.Workbooks.Open "C:\Users\...\WorkbookA.xlsx" NxlApp.Visible = True 'Perform actions on WorkbookA (keep it open) Set ExcelApp = GetObject("", "Excel.Application.14") xlApp.Workbooks.Open "C:\Users\...\WorkbookB.xlsx" xlApp.Visible = True 'Perform actions on WorkbookB (keep it open) 'Go back to WorkbookA (using the xlApp variable this time) xlApp.Workbook("A.xlsx")... </code></pre>
19,822,626
2
3
null
2013-11-06 19:50:13.8 UTC
null
2015-10-26 23:15:56.273 UTC
2015-10-26 23:15:56.273 UTC
user4039065
null
null
2,830,928
null
1
7
vba|excel|instance|excel.application
43,443
<p>The excel application can have several workbooks open at once so you don't need to instancing a new one. If you from inside excel you should not need to reference the application to open workbooks. You might wish to create several workbook instances e.g.</p> <pre><code>Dim wbWorkbookA As Workbook Dim wbWorkbookB As Workbook Set wbWorkbookA = Workbooks.Open("C:\Users\...\WorkbookA.xlsx") Set wbWorkbookB = Workbooks.Open("C:\Users\...\WorkbookB.xlsx") </code></pre> <p>This will open the workbooks and give a reference so that you can manipulate them using your code.</p>
56,262,515
How to handle dependencies array for custom hooks in react
<p>I'm creating a custom hook and would like to define an optional param so that I can pass in extra dependencies when needed. My code looks like the following snippet:</p> <pre><code>import { useEffect } from 'react'; function useCustomHook(param1, extraDeps) { useEffect(() =&gt; { // do something with param1 here }, [param1, ...extraDeps]) } </code></pre> <p>The react-hooks/exhaustive-deps throws a warning saying </p> <blockquote> <p>React Hook useEffect has a spread element in its dependency array. This means we can't statically verify whether you've passed the correct dependencies</p> </blockquote> <p>Anyone have an idea about how to address that warning? Or it's not a good practice to pass deps array to custom hook?</p> <p>For those who are interested in why extraDeps is needed. here's an example:</p> <pre><code>const NewComponent = (props) =&gt; { [field1, setField1] = useState() [field2, setField2] = useState() // I only want this to be called when field1 change useCustomHook('.css-selector', [field1]); return &lt;div&gt;{field1}{field2}&lt;/div&gt;; } </code></pre>
67,802,751
6
8
null
2019-05-22 17:59:19.573 UTC
5
2022-07-14 01:10:09.07 UTC
2019-05-22 20:16:43.083 UTC
null
1,783,403
null
1,783,403
null
1
34
reactjs|react-hooks
17,244
<p>I've found a useful alternative to the solutions proposed here. As mentioned <a href="https://www.reddit.com/r/reactjs/comments/dgbn15/pass_a_dependency_array_to_a_custom_hook/f3az9nh?utm_source=share&amp;utm_medium=web2x&amp;context=3" rel="noreferrer">in this Reddit topic</a>, the React team apparently recommends something like:</p> <pre><code>// Pass the callback as a dep cost useCustomHook = callback =&gt; { useEffect(() =&gt; { /* do something */ }, [callback]) }; // Then the user wraps the callback in `useMemo` to avoid running the effect too often // Whenever the deps change, useMemo will ensure that the callback changes, which will cause effect to re-run useCustomHook( useMemo(() =&gt; { /* do something }, [a, b, c]) ); </code></pre> <p>I've used this technique and it worked very nicely.</p>
1,279,681
mod_rewrite: replace underscores with dashes
<p>I'm revealing my embarrassing ignorance of REGEX-fu here, but: I currently have a website where a load of the articles' URLs are written as "article_name", whilst the newer ones are written as "article-name".</p> <p>I want to move all of them to using dashes, so is there a regular expression I could use to rewrite the older URLs to their newer equivalents?</p> <p>Thanking you in advance!</p>
1,279,758
5
0
null
2009-08-14 19:17:36.523 UTC
13
2011-01-12 10:31:57.147 UTC
null
null
null
null
50,189
null
1
20
regex|mod-rewrite
29,867
<p>First you must achieve consistency in the existing URLs. Basically, you have to normalize all existing names to always use dashes. Ok, you've done that.</p> <p>We're starting with the following assumption:</p> <p>The URL is roughly of the form:</p> <pre> http://example.com/articles/what-ever/really-doesnt_matter/faulty_article_name </pre> <p>where only URLs under <code>/articles</code> should be rewritten, and only the <code>/faulty_article_name</code> part needs to be sanitized. </p> <h3>Greatly updated, with something that actually works</h3> <p>For Apache:</p> <pre><code>RewriteEngine On RewriteRule ^(/?articles/.*/[^/]*?)_([^/]*?_[^/]*)$ $1-$2 [N] RewriteRule ^(/?articles/.*/[^/]*?)_([^/_]*)$ $1-$2 [R=301] </code></pre> <p>That's generally inspired by GApple's answer.</p> <p>The first <code>/?</code> ensures that this code will run on both vhost confs and <code>.htaccess</code> files. The latter does not expect a leading slash.</p> <p>I then add the <code>articles/</code> part to ensure that the rules only apply for URLs within <code>/articles</code>.</p> <p>Then, while we have at least two underscores in the URL, we keep looping through the rules. When we end up with only one remaining underscore, the second rule kicks in, replaces it with a dash, and does a permanent redirect.</p> <p>Phew.</p>
622,481
Django + Ajax
<p>So, I am just starting to use jQuery with one of my Django projects, but I have a pretty noobie question.</p> <p>In a django view you have to return an HttpResponse object from the view, but sometimes I don't need to return anything. For instance, I might just be updating the database via ajax and don't need to send anything back. So my question is, what do you do in that situation?</p> <p>Thanks</p>
622,525
5
0
null
2009-03-07 20:50:59.783 UTC
11
2010-05-30 13:07:36.48 UTC
null
null
null
Nate
74,474
null
1
21
jquery|django
4,203
<p>An HTTP response is more than sending content to the browser. A response is associated with a status code and several HTTP headers. Additionally, a response may contain a body (actual content).</p> <p>I think it's OK to sent an HttpResponse object with no body. That is:</p> <pre><code>return HttpResponse() </code></pre> <p>This will send an HTTP response with status code 200 OK, which is exactly what happened on the server side, i.e. the operation succeeded, everything is OK. Although there are better ways, see below.</p> <p><a href="http://en.wikipedia.org/wiki/Representational_State_Transfer" rel="noreferrer">Restfully</a> speaking, when the operation encountered problems, you should return an HTTP response with an appropriate <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html" rel="noreferrer">status code</a>. Like one of the 5XX status codes which designate server side errors.</p> <p>Now, looking at all those HTTP status codes we see a 201 Created status code which is a more appropriate code than 200 OK when you're storing that POST data somewhere, like a DB. In this case you should be doing something like this in your view:</p> <pre><code>return HttpResponse(status=201) </code></pre> <p>And, as someone already mentioned, you could take advantage of these status codes in your JavaScript so that you can present a user a more informative message or maybe choose some other strategy for your requests.</p>
451,922
how do I grep through a mysql database?
<p>Looking for a nifty helper function/method for grepping through all defined tables, columns, stored procedures, etc, for a MySql database.</p> <p>I had something similar for SQL Server.</p>
451,957
5
1
null
2009-01-16 20:42:43.567 UTC
9
2019-01-09 15:25:20.903 UTC
null
null
null
someguy
39,529
null
1
23
mysql|grep
39,870
<p>In the INFORMATION_SCHEMA database:</p> <pre><code>select * from columns WHERE TABLE_NAME LIKE '%tablename%' AND COLUMN_NAME LIKE '%columnname%' </code></pre> <p>More info here: <a href="http://dev.mysql.com/doc/refman/5.0/en/information-schema.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/information-schema.html</a></p> <p>Ok, it doesn't completely answer your question but you should be able to put it together how you want from here.</p>
1,200,562
Difference in JSON objects using Javascript/JQuery
<p>I have two JSON objects in Javascript, identical except for the numerical values. It looks like this:</p> <pre><code>var data = { "eth0":{"Tx":"4136675","Rx":"13232319"}, "eth1":{"Tx":"4","Rx":"0"}, "lo":{"Tx":"471290","Rx":"471290"} } var old = { "eth0":{"Tx":"4136575","Rx":"13232219"}, "eth1":{"Tx":"4","Rx":"0"}, "lo":{"Tx":"471290","Rx":"471290"} } </code></pre> <p>One object called "data" has the current values, another object called "old" has the same values from 1 second ago. I'd like to output a JSON object with only the <em>change</em> in values so I can calculate data throughput on the network interfaces.</p> <pre><code>var throughput = { "eth0":{"Tx":"100","Rx":"100"}, "eth1":{"Tx":"0","Rx":"0"}, "lo":{"Tx":"0","Rx":"0"} } </code></pre> <p>I'm not sure how to go about traversing the JSON data - it could be for any number of interfaces.</p> <p>Can anyone please lend me a hand? Thanks in advance</p>
1,200,865
6
3
null
2009-07-29 14:14:02.717 UTC
14
2021-01-13 01:08:04.39 UTC
null
null
null
null
147,150
null
1
18
javascript|jquery|json
25,261
<p>You can iterate through the parent and child object properties:</p> <pre><code>var diff = {}; for(var p in data){ if (old.hasOwnProperty(p) &amp;&amp; typeof(data[p]) == 'object'){ diff[p] = {}; for(var i in data[p]){ if (old[p].hasOwnProperty(i)){ diff[p][i] = data[p][i] - old[p][i]; } } } } </code></pre>
918,990
C# - Capturing the Mouse cursor image
<h2>BACKGROUND</h2> <ul> <li>I am writing a screen capture application</li> <li>My code is based derived from this project: <a href="http://www.codeproject.com/KB/cs/DesktopCaptureWithMouse.aspx?display=Print" rel="noreferrer">http://www.codeproject.com/KB/cs/DesktopCaptureWithMouse.aspx?display=Print</a></li> <li>Note that the code captures the the mouse cursor also (which is desirable for me)</li> </ul> <h2>MY PROBLEM</h2> <ul> <li>Code works fine when the mouse cursor is the normal pointer or hand icon - the mouse is rendered correctly on the screenshot</li> <li>However, when the mouse cursor is changed to the insertion point (the "I-beam" cursor) - for example typing in NOTEPAD - then code doesn't work - the result is that I get a faint image of the cursor - like a very translucent (gray) version of it instead of the blank &amp; white one would expect.</li> </ul> <h2>MY QUESTION</h2> <ul> <li>How can I capture the mouse cursor image when the image is one of these "I-beam"-type images</li> <li>NOTE: If you click on the original article someone offers a suggestion - it doesn't work</li> </ul> <h2>SOURCE</h2> <p>This is from the original article. </p> <pre><code> static Bitmap CaptureCursor(ref int x, ref int y) { Bitmap bmp; IntPtr hicon; Win32Stuff.CURSORINFO ci = new Win32Stuff.CURSORINFO(); Win32Stuff.ICONINFO icInfo; ci.cbSize = Marshal.SizeOf(ci); if (Win32Stuff.GetCursorInfo(out ci)) { if (ci.flags == Win32Stuff.CURSOR_SHOWING) { hicon = Win32Stuff.CopyIcon(ci.hCursor); if (Win32Stuff.GetIconInfo(hicon, out icInfo)) { x = ci.ptScreenPos.x - ((int)icInfo.xHotspot); y = ci.ptScreenPos.y - ((int)icInfo.yHotspot); Icon ic = Icon.FromHandle(hicon); bmp = ic.ToBitmap(); return bmp; } } } return null; } </code></pre>
1,020,819
6
2
null
2009-05-28 02:53:53.4 UTC
13
2021-12-22 22:50:53.913 UTC
2021-12-22 22:50:53.913 UTC
null
4,294,399
null
13,477
null
1
32
c#|icons|screenshot|mouse-cursor
25,612
<p>While I can't explain exactly why this happens, I think I can show how to get around it.</p> <p>The ICONINFO struct contains two members, hbmMask and hbmColor, that contain the mask and color bitmaps, respectively, for the cursor (see the MSDN page for <a href="http://msdn.microsoft.com/en-us/library/ms929934.aspx" rel="noreferrer">ICONINFO</a> for the official documentation).</p> <p>When you call GetIconInfo() for the default cursor, the ICONINFO struct contains both valid mask and color bitmaps, as shown below (Note: the red border has been added to clearly show the image boundaries):</p> <p><strong>Default Cursor Mask Bitmap</strong> <a href="https://i.stack.imgur.com/QlCof.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QlCof.png" alt="default cursor mask bitmap image"></a></p> <p><strong>Default Cursor Color Bitmap</strong> <a href="https://i.stack.imgur.com/YyuI8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YyuI8.png" alt="default cursor color bitmap image"></a></p> <p>When Windows draws the default cursor, the mask bitmap is first applied with an AND raster operation, then the color bitmap is applied with an XOR raster operation. This results in an opaque cursor and a transparent background.</p> <p>When you call GetIconInfo() for the I-Beam cursor, though, the ICONINFO struct only contains a valid mask bitmap, and no color bitmap, as shown below (Note: again, the red border has been added to clearly show the image boundaries):</p> <p><strong>I-Beam Cursor Mask Bitmap</strong> <a href="https://i.stack.imgur.com/O5iAp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/O5iAp.png" alt="ibeam cursor mask bitmap image"></a> </p> <p>According to the ICONINFO documentation, the I-Beam cursor is then a monochrome cursor. The top half of the mask bitmap is the AND mask, and the bottom half of the mask bitmap is the XOR bitmap. When Windows draws the I-Beam cursor, the top half of this bitmap is first drawn over the desktop with an AND raster operation. The bottom half of the bitmap is then drawn over top with an XOR raster operation. Onscreen, The cursor will appear as the inverse of the content behind it.</p> <p>One of the <a href="http://www.codeproject.com/Messages/1408725/Have-you-solved-the-IBeam-cursor-problem.aspx" rel="noreferrer">comments</a> for the original article that you linked mentions this. On the desktop, since the raster operations are applied over the desktop content, the cursor will appear correct. However, when the image is drawn over no background, as in your posted code, the raster operations that Windows performs result in a faded image.</p> <p>That being said, this updated CaptureCursor() method will handle both color and monochrome cursors, supplying a plain black cursor image when the cursor is monochrome.</p> <pre><code>static Bitmap CaptureCursor(ref int x, ref int y) { Win32Stuff.CURSORINFO cursorInfo = new Win32Stuff.CURSORINFO(); cursorInfo.cbSize = Marshal.SizeOf(cursorInfo); if (!Win32Stuff.GetCursorInfo(out cursorInfo)) return null; if (cursorInfo.flags != Win32Stuff.CURSOR_SHOWING) return null; IntPtr hicon = Win32Stuff.CopyIcon(cursorInfo.hCursor); if (hicon == IntPtr.Zero) return null; Win32Stuff.ICONINFO iconInfo; if (!Win32Stuff.GetIconInfo(hicon, out iconInfo)) return null; x = cursorInfo.ptScreenPos.x - ((int)iconInfo.xHotspot); y = cursorInfo.ptScreenPos.y - ((int)iconInfo.yHotspot); using (Bitmap maskBitmap = Bitmap.FromHbitmap(iconInfo.hbmMask)) { // Is this a monochrome cursor? if (maskBitmap.Height == maskBitmap.Width * 2) { Bitmap resultBitmap = new Bitmap(maskBitmap.Width, maskBitmap.Width); Graphics desktopGraphics = Graphics.FromHwnd(Win32Stuff.GetDesktopWindow()); IntPtr desktopHdc = desktopGraphics.GetHdc(); IntPtr maskHdc = Win32Stuff.CreateCompatibleDC(desktopHdc); IntPtr oldPtr = Win32Stuff.SelectObject(maskHdc, maskBitmap.GetHbitmap()); using (Graphics resultGraphics = Graphics.FromImage(resultBitmap)) { IntPtr resultHdc = resultGraphics.GetHdc(); // These two operation will result in a black cursor over a white background. // Later in the code, a call to MakeTransparent() will get rid of the white background. Win32Stuff.BitBlt(resultHdc, 0, 0, 32, 32, maskHdc, 0, 32, Win32Stuff.TernaryRasterOperations.SRCCOPY); Win32Stuff.BitBlt(resultHdc, 0, 0, 32, 32, maskHdc, 0, 0, Win32Stuff.TernaryRasterOperations.SRCINVERT); resultGraphics.ReleaseHdc(resultHdc); } IntPtr newPtr = Win32Stuff.SelectObject(maskHdc, oldPtr); Win32Stuff.DeleteObject(newPtr); Win32Stuff.DeleteDC(maskHdc); desktopGraphics.ReleaseHdc(desktopHdc); // Remove the white background from the BitBlt calls, // resulting in a black cursor over a transparent background. resultBitmap.MakeTransparent(Color.White); return resultBitmap; } } Icon icon = Icon.FromHandle(hicon); return icon.ToBitmap(); } </code></pre> <p>There are some issues with the code that may or may not be a problem.</p> <ol> <li>The check for a monochrome cursor simply tests whether the height is twice the width. While this seems logical, the ICONINFO documentation does not mandate that only a monochrome cursor is defined by this.</li> <li>There is probably a better way to render the cursor that the BitBlt() - BitBlt() - MakeTransparent() combination of method calls I used.</li> </ol>
813,529
Documentation-generator for Objective-C?
<p>Is there a generally-accepted documentation generator for Objective-C (similar to RDoc for Ruby)? I've seen Doxygen and ObjcDoc, and am wondering which is most widely used.</p>
813,791
6
0
null
2009-05-01 22:15:52.46 UTC
21
2018-12-12 11:08:45.263 UTC
2009-06-04 01:35:46.813 UTC
null
99,646
null
99,646
null
1
49
objective-c|documentation
21,314
<p><a href="http://www.doxygen.nl" rel="nofollow noreferrer">Doxygen</a> is probably the most widely used option. Because it's not just for ObjC (doxygen supports many other languages), the development is lively and the community quite strong. <a href="http://developer.apple.com/opensource/tools/headerdoc.html" rel="nofollow noreferrer">HeaderDoc</a> (now an open source project), by comparison appears to have largely stagnated. HeaderDoc only produces HTML output, while doxygen also produces PDF, LaTeX and many other output forms besides HTML. Even Apple seems to recommend doxygen, with <a href="http://developer.apple.com/library/ios/#featuredarticles/DoxygenXcode/_index.html" rel="nofollow noreferrer">this</a> guide to automatically producing documentation sets, compatible with Xcode's help viewer, from within your Xcode build process. </p> <p>It's worth noting that doxygen can read HeaderDoc-style comments, so you can write your documentation in HeaderDoc style and decide later whether to produce the final output using doxygen or HeaderDoc.</p>
836,601
What's the difference between [NSNull null] and nil?
<p>Here's a context where I have seen that:</p> <pre><code>NSMutableArray *controllers = [[NSMutableArray alloc] init]; for (unsigned i = 0; i &lt; kNumberOfPages; i++) { [controllers addObject:[NSNull null]]; } </code></pre> <p>why not nil in that place?</p>
836,624
6
1
null
2009-05-07 19:39:05.75 UTC
11
2018-03-15 11:44:37.263 UTC
2014-01-24 13:27:34.307 UTC
null
1,698,467
null
62,553
null
1
50
objective-c|cocoa-touch|cocoa|null|nsnull
31,002
<p>Directly from <a href="https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/NumbersandValues/Articles/Null.html" rel="noreferrer">Apple</a>:</p> <blockquote> <p>The NSNull class defines a singleton object you use to represent null values in situations where nil is prohibited as a value (typically in a collection object such as an array or a dictionary).</p> </blockquote> <p>So in your example, that's exactly what's happening, the programmer is choosing to put a null object into the controllers array, where nil is not allowed as a value.</p>
233,328
How do I print the full value of a long string in gdb?
<p>I want to print the full length of a C-string in GDB. By default it's being abbreviated, how do I force GDB to print the whole string?</p>
233,339
6
0
null
2008-10-24 12:36:01.353 UTC
129
2018-04-20 09:17:32.577 UTC
2011-10-06 21:11:12.36 UTC
therefromhere
8,331
therefromhere
8,331
null
1
436
c++|c|string|debugging|gdb
242,574
<pre><code>set print elements 0 </code></pre> <p><a href="http://ftp.gnu.org/old-gnu/Manuals/gdb-5.1.1/html_node/gdb_57.html#IDX353" rel="noreferrer">From the GDB manual</a>: </p> <blockquote><code>set print elements </code><i><code>number-of-elements</code></i></blockquote> <blockquote> Set a limit on how many elements of an array GDB will print. If GDB is printing a large array, it stops printing after it has printed the number of elements set by the <code>set print elements</code> command. This limit also applies to the display of strings. When GDB starts, this limit is set to 200. <b>Setting <i>number-of-elements</i> to zero means that the printing is unlimited</b>. </blockquote>
31,172,003
Java - Write hashmap to a csv file
<p>I have a hashmap with a String key and String value. It contains a large number of keys and their respective values.</p> <p>For example:</p> <pre><code>key | value abc | aabbcc def | ddeeff </code></pre> <p>I would like to write this hashmap to a csv file such that my csv file contains rows as below:</p> <pre><code>abc,aabbcc def,ddeeff </code></pre> <p>I tried the following example here using the supercsv library: <a href="http://javafascination.blogspot.com/2009/07/csv-write-using-java.html" rel="nofollow noreferrer">http://javafascination.blogspot.com/2009/07/csv-write-using-java.html</a>. However, in this example, you have to create a hashmap for each row that you want to add to your csv file. I have a large number of key value pairs which means that several hashmaps, with each containing data for one row need to be created. I would like to know if there is a more optimized approach that can be used for this use case.</p>
31,196,047
6
2
null
2015-07-01 21:27:34.393 UTC
4
2021-04-26 04:22:09.68 UTC
2021-04-25 09:07:05.703 UTC
null
6,296,561
null
3,469,521
null
1
12
java|csv|hashmap|supercsv
45,823
<p>As your question is asking how to do this using Super CSV, I thought I'd chime in (as a maintainer of the project).</p> <p>I initially thought you could just iterate over the map's entry set using <code>CsvBeanWriter</code> and a name mapping array of <code>"key", "value"</code>, but this doesn't work because <code>HashMap</code>'s internal implementation doesn't allow reflection to get the key/value.</p> <p>So your only option is to use <code>CsvListWriter</code> as follows. At least this way you don't have to worry about escaping CSV (every other example here just joins with commas...aaarrggh!):</p> <pre><code>@Test public void writeHashMapToCsv() throws Exception { Map&lt;String, String&gt; map = new HashMap&lt;&gt;(); map.put("abc", "aabbcc"); map.put("def", "ddeeff"); StringWriter output = new StringWriter(); try (ICsvListWriter listWriter = new CsvListWriter(output, CsvPreference.STANDARD_PREFERENCE)){ for (Map.Entry&lt;String, String&gt; entry : map.entrySet()){ listWriter.write(entry.getKey(), entry.getValue()); } } System.out.println(output); } </code></pre> <p>Output:</p> <pre><code>abc,aabbcc def,ddeeff </code></pre>
31,078,710
How to obtain Telegram chat_id for a specific user?
<p>How to obtain user <code>chat_id</code> in Telegram bot API? The documentation says:</p> <blockquote> <p>Integer | Unique identifier for the message recipient — User or GroupChat id</p> </blockquote>
31,081,941
10
3
null
2015-06-26 17:16:30.9 UTC
19
2022-07-24 02:52:02.893 UTC
2019-04-14 13:26:10.507 UTC
null
3,592,207
null
3,592,207
null
1
77
telegram-bot
257,582
<p>The message updates you receive via <code>getUpdates</code> or your webhook will contain the chat ID for the specific message. It will be contained under the <code>message.chat.id</code> key.</p> <p>This seems like the only way you are able to retrieve the chat ID. So if you want to write something where the bot initiates the conversation you will probably have to store the chat ID in relation to the user in some sort of key->value store like MemCache or Redis. </p> <p>I believe their documentation suggests something similar here, <a href="https://core.telegram.org/bots#deep-linking-example">https://core.telegram.org/bots#deep-linking-example</a>. You can use <strong>deep-linking</strong> to initiate a conversation without requiring the user to type a message first.</p>
31,205,599
ASP.NET Web API : Correct way to return a 401/unauthorised response
<p>I have an MVC webapi site that uses OAuth/token authentication to authenticate requests. All the relevant controllers have the right attributes, and authentication is working ok. </p> <p>The problem is that not all of the request can be authorised in the scope of an attribute - some authorisation checks have to be performed in code that is called by controller methods - what is the correct way to return a 401 unauthorised response in this case?</p> <p>I have tried <code>throw new HttpException(401, "Unauthorized access");</code>, but when I do this the response status code is 500 and I get also get a stack trace. Even in our logging DelegatingHandler we can see that the response is 500, not 401. </p>
31,206,850
9
3
null
2015-07-03 11:20:16.833 UTC
12
2022-07-27 19:39:49.953 UTC
2015-07-03 12:02:50.63 UTC
null
55,847
null
1,324,393
null
1
142
c#|asp.net-mvc|authorization
192,597
<p>You should be throwing a <a href="https://msdn.microsoft.com/en-us/library/system.web.http.httpresponseexception.aspx"><code>HttpResponseException</code></a> from your API method, not <a href="https://msdn.microsoft.com/en-us/library/system.web.httpexception.aspx"><code>HttpException</code></a>:</p> <pre><code>throw new HttpResponseException(HttpStatusCode.Unauthorized); </code></pre> <p>Or, if you want to supply a custom message:</p> <pre><code>var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Oops!!!" }; throw new HttpResponseException(msg); </code></pre>
20,985,252
Detect when application is idle in Android
<p>I am developing an application that will be running in Kiosk Mode. In this application, if the user didn't do anything in the application within 5 minutes, the application will show a screen saver that is the logo of the application. </p> <p>My question is, <strong>how can I code on detecting IDLE within 5 minutes?</strong></p>
20,985,418
4
4
null
2014-01-08 01:13:23.083 UTC
9
2020-01-13 09:21:04.253 UTC
null
null
null
null
2,503,743
null
1
13
android
16,827
<p>I think you could use <a href="http://developer.android.com/reference/android/app/Activity.html#dispatchTouchEvent(android.view.MotionEvent)" rel="nofollow noreferrer">http://developer.android.com/reference/android/app/Activity.html#dispatchTouchEvent(android.view.MotionEvent)</a> and <a href="http://developer.android.com/reference/android/app/Activity.html#dispatchKeyEvent(android.view.KeyEvent)" rel="nofollow noreferrer">http://developer.android.com/reference/android/app/Activity.html#dispatchKeyEvent(android.view.KeyEvent)</a> in your App to set a timestamp everytime a userinteraction takes place (simply override the methods and return false at the end so that the events will be propagated to underlying views) - then you can use some kind of timer which checks for the last timestamp of interaction recurringly and trigger your screen saver if your 5 minutes IDLE time are reached.</p> <p>So in an Activity you simply override the before mentioned Methods like this:</p> <pre><code>@Override public boolean dispatchTouchEvent (MotionEvent ev) { timestamp = System.getCurrentTimeMilis(); return false; // return false to indicate that the event hasn't been handled yet } </code></pre> <p>The dispatchKeyEvent and the other methods which you can override to determine user-activity should work fairly similar.</p> <p>If you're using more than one Activity you may want to create a base class which extends Activity and Override all the dispatchXXXEvent you want to handle and which you than use as base class of all your Activities. But I guess the details of your implementation may be a little bit out of scope for the actual question :)</p> <p>For the different possibilities of timers you may find useful info here: <a href="https://stackoverflow.com/questions/14376470/scheduling-recurring-task-in-android">Scheduling recurring task in Android</a></p>
44,297,430
Generate War file using Maven
<p>I have a maven pom as follows:</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;MerchantWallet&lt;/groupId&gt; &lt;artifactId&gt;StellarReceive&lt;/artifactId&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;name&gt;StellarReceive Maven Webapp&lt;/name&gt; &lt;url&gt;http://maven.apache.org&lt;/url&gt; &lt;properties&gt; &lt;spring.version&gt;4.3.8.RELEASE&lt;/spring.version&gt; &lt;jdk.version&gt;1.8&lt;/jdk.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;jstl&lt;/groupId&gt; &lt;artifactId&gt;jstl&lt;/artifactId&gt; &lt;version&gt;1.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-jdbc&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-core&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-web&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- hello --&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;3.8.1&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;mysql&lt;/groupId&gt; &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt; &lt;version&gt;5.1.6&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;finalName&gt;StellarReceive&lt;/finalName&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;3.0&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;${jdk.version}&lt;/source&gt; &lt;target&gt;${jdk.version}&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>I dont see a .war file in the target folder. Can someone please help</p> <p>Here is my folder structure: <a href="https://i.stack.imgur.com/S1d1G.png" rel="noreferrer"><img src="https://i.stack.imgur.com/S1d1G.png" alt="enter image description here"></a></p>
44,304,948
3
2
null
2017-06-01 02:13:43.78 UTC
2
2019-02-14 14:51:15.573 UTC
2017-06-01 02:32:46.24 UTC
user177800
null
null
547,198
null
1
25
java|maven|tomcat
92,902
<p>First you must define your project with as packaging of war type:</p> <pre><code>&lt;groupId&gt;...&lt;/groupId&gt; &lt;artifactId&gt;...&lt;/artifactId&gt; &lt;version&gt;...&lt;/version&gt; &lt;packaging&gt;war&lt;/packaging&gt; </code></pre> <p>Then you will need to use the maven plugin to generate the war when compiling:</p> <pre><code>&lt;plugin&gt; &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;attachClasses&gt;true&lt;/attachClasses&gt; &lt;webXml&gt;target/web.xml&lt;/webXml&gt; &lt;webResources&gt; &lt;resource&gt; &lt;directory&gt;src/main/webapp&lt;/directory&gt; &lt;filtering&gt;true&lt;/filtering&gt; &lt;/resource&gt; &lt;/webResources&gt; &lt;/configuration&gt; &lt;/plugin&gt; </code></pre>
17,944,061
how to use number picker with dialog
<p>I want to use a number picker for the purpose of getting the discount percentage from the user. once the user enters the sale price, i want a dialog box to appear asking for the discount percentage. I cannot find a way to integrate the numberpicker in the dialog.</p>
17,944,205
4
1
null
2013-07-30 10:05:09.493 UTC
6
2018-06-01 02:08:14.407 UTC
null
null
null
null
2,432,126
null
1
22
android|dialog|numberpicker
52,763
<p>I have made a small demo of NumberPicker. This may not be perfect but you can use and modify the same. </p> <p>Use a custom dialog and set the number picker. </p> <p>More info @</p> <p><a href="http://developer.android.com/reference/android/widget/NumberPicker.html" rel="noreferrer">http://developer.android.com/reference/android/widget/NumberPicker.html</a></p> <pre><code>public class MainActivity extends Activity implements NumberPicker.OnValueChangeListener { private TextView tv; static Dialog d ; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.textView1); Button b = (Button) findViewById(R.id.button11);// on click of button display the dialog b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { show(); } }); } @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { Log.i("value is",""+newVal); } public void show() { final Dialog d = new Dialog(MainActivity.this); d.setTitle("NumberPicker"); d.setContentView(R.layout.dialog); Button b1 = (Button) d.findViewById(R.id.button1); Button b2 = (Button) d.findViewById(R.id.button2); final NumberPicker np = (NumberPicker) d.findViewById(R.id.numberPicker1); np.setMaxValue(100); // max value 100 np.setMinValue(0); // min value 0 np.setWrapSelectorWheel(false); np.setOnValueChangedListener(this); b1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { tv.setText(String.valueOf(np.getValue())); //set the value to textview d.dismiss(); } }); b2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { d.dismiss(); // dismiss the dialog } }); d.show(); } } </code></pre> <p>activity_main.xml</p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" &gt; &lt;TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /&gt; &lt;Button android:id="@+id/button11" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:text="Open" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>dialog.xml</p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" &gt; &lt;NumberPicker android:id="@+id/numberPicker1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="64dp" /&gt; &lt;Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/numberPicker1" android:layout_marginLeft="20dp" android:layout_marginTop="98dp" android:layout_toRightOf="@+id/numberPicker1" android:text="Cancel" /&gt; &lt;Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/button2" android:layout_alignBottom="@+id/button2" android:layout_marginRight="16dp" android:layout_toLeftOf="@+id/numberPicker1" android:text="Set" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>Snap shot</p> <p><img src="https://i.stack.imgur.com/3m41J.png" alt="enter image description here"></p>
33,441,873
AWS error - sudo: unable to resolve host ip-10-0-xx-xx
<p>I launched a new <code>aws</code> instance. My private ip is <code>ip-10-0-xx-xx</code> as per amazon console. Everytime when I do a sudo command, I get the following error </p> <pre><code>sudo: unable to resolve host ip-10-0-xx-xx </code></pre> <p>How can I rectify this error? </p>
33,442,052
11
3
null
2015-10-30 17:40:13.66 UTC
12
2022-07-19 17:55:32.38 UTC
null
null
null
null
826,610
null
1
75
amazon-web-services|sudo
61,448
<p><strong>You should enable the DNS hostnames on your VPC</strong>: <a href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-dns.html#vpc-dns-updating" rel="nofollow noreferrer">http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-dns.html#vpc-dns-updating</a></p> <p><em>If for some reason, you cannot enable it, you can still use the <code>/etc/hosts</code> to make it resolve, but this is definitely not the recommended solution</em></p> <pre><code>10.0.xx.xx ip-10-0-xx-xx </code></pre>
23,102,193
org.springframework.beans.NotWritablePropertyException: Invalid property 'adminEmails' of bean class
<p>I got stuck on this error given below:</p> <p><strong>Stack Trace</strong></p> <pre><code>Apr 16, 2014 12:21:23 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [beans.xml] Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'collectionsWithProps' defined in class path resource [beans.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'adminEmails' of bean class [com.student.spring.impl.CollectionsWithProps]: Bean property 'adminEmails' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter? at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1396) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) at com.student.spring.test.MyTest.main(MyTest.java:26) Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'adminEmails' of bean class [com.student.spring.impl.CollectionsWithProps]: Bean property 'adminEmails' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter? at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1064) at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:924) at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:76) at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1393) ... 8 more </code></pre> <p>Here is my <strong>MyTest.java</strong></p> <pre><code>package com.student.spring.test; import java.util.Properties; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import com.student.spring.impl.CollectionsWithProps; @SuppressWarnings("deprecation") public class MyTest { public static void main(String[] args) { Resource resource = new ClassPathResource("beans.xml"); BeanFactory beanFactory = new XmlBeanFactory(resource); CollectionsWithProps cWP = (CollectionsWithProps) beanFactory .getBean("collectionsWithProps"); System.out.println(cWP); } } </code></pre> <p>Here is <strong>CollectionsWithProps.java</strong></p> <pre><code>package com.student.spring.impl; import java.util.Properties; public class CollectionsWithProps { private Properties emails=null; public Properties getEmails() { return emails; } public void setEmails(Properties emails) { this.emails = emails; } public String toString(){ return "College [Props=" + emails + "]"; } } </code></pre> <p>Here is my <strong>beans.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"&gt; &lt;bean id="collectionsWithProps" class="com.student.spring.impl.CollectionsWithProps"&gt; &lt;property name="adminEmails"&gt; &lt;props&gt; &lt;prop key="admin"&gt;[email protected]&lt;/prop&gt; &lt;prop key="support"&gt;[email protected]"&gt;&lt;/prop&gt; &lt;prop key="hr"&gt;[email protected]&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre>
23,102,342
4
2
null
2014-04-16 06:58:18.533 UTC
null
2022-04-15 09:56:23.353 UTC
2014-11-24 16:26:36.583 UTC
null
3,885,376
null
3,257,643
null
1
8
java|spring
51,789
<p>In <code>beans.xml</code> you are trying to set the field <code>adminEmails</code> of <code>CollectionsWithProps</code>. However the class doesn't have that field, it has the <code>emails</code> field.</p> <p>Either fix <code>beans.xml</code> to use emails instead of <code>adminEmails</code>, or fix the source code of <code>CollectionsWithProps</code> be renaming <code>emails</code> to <code>adminEmails</code> (along with the getters and setters)</p>
2,082,064
How to install Doxygen GUI on Ubuntu?
<p>I can't figure out how to install the Doxygen GUI (doxywizard) on Ubuntu. Where can I get it?</p>
2,082,095
5
0
null
2010-01-17 18:19:51.22 UTC
4
2016-07-07 13:26:30.607 UTC
2016-07-07 13:26:30.607 UTC
null
895,245
null
217,649
null
1
19
doxygen|doxywizard
45,918
<p>In Debian the package is called doxygen-gui. It must be the same in Ubuntu, so try <code>sudo apt-get install doxygen-gui</code>.</p> <p>Edit : apparently, doxygen-gui doesn't exist in Karmic. Try any other repo ? <a href="http://packages.ubuntu.com/search?keywords=doxygen-gui" rel="noreferrer">http://packages.ubuntu.com/search?keywords=doxygen-gui</a></p>
1,402,112
How do I check if the key pressed on a form field is a digit (0 - 9)?
<p>I'm using the <code>onkeyup</code> event on a form field in JavaScript, and I'm wanting to check if the key the key pressed is a numeric digit - i.e. 0 - 9, so I can then do something with the input.</p> <pre><code>&lt;input type=&quot;text&quot; onkeyup=&quot;&quot; /&gt; </code></pre> <p>Would I need to use Regex for this?</p>
1,402,138
6
0
null
2009-09-09 21:07:25 UTC
3
2021-08-13 14:25:51.163 UTC
2020-12-10 21:14:35.237 UTC
null
4,370,109
null
1,692
null
1
17
javascript|dom-events
39,064
<p>See these:</p> <ul> <li><a href="https://stackoverflow.com/questions/469357/html-text-input-allow-only-numeric-input">HTML Text Input allow only Numeric input</a></li> <li><a href="https://stackoverflow.com/questions/724217/allow-digits-only-for-inputs">allow digits only for inputs</a></li> </ul>
2,060,382
How would one check for installed MATLAB toolboxes in a script/function?
<p>How would one check for installed MATLAB toolboxes in a script/function? (checking toolbox versions would also be good!) This could provide a quick and useful error message when someone attempts to run a script without a required toolbox.</p> <p>A quick, albeit rough, solution that comes to mind is parsing the text output of the <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/ver.html" rel="noreferrer"><code>ver</code></a> command. I wonder if there's a better way.</p> <p>Some quick searching revealed <code>ver product</code> or the <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/license.html" rel="noreferrer"><code>license</code></a> function with the <code>'test'</code> argument may be useful, but I could not find a mapping of toolbox names (ie. <code>'Image Processing Toolbox'</code>) to product names (ie. <code>'control'</code>) or feature names (ie. <code>image_toolbox</code>).</p> <p>Furthermore, when I ran <code>license('inuse')</code>, I only received the following:</p> <pre> >> a = license('inuse'); a a = feature: 'matlab' user: &lt;username&gt; </pre> <p>I hoped for a list of the many toolboxes I have access to.</p> <p>This question was prompted by trying to test a co-workers script early. Unfortunately, it required the Image Processing Toolbox, which I currently lack. A useful error message would've saved time trying to diagnose the problem. Now I'll wait for a compiled version before testing it.</p>
2,061,547
6
0
null
2010-01-13 21:23:58.157 UTC
15
2018-04-10 15:44:50.197 UTC
2011-11-14 15:25:22.717 UTC
null
97,160
null
15,286
null
1
35
matlab
95,074
<p>One drawback to the <a href="https://www.mathworks.com/help/matlab/ref/ver.html" rel="nofollow noreferrer"><code>ver</code></a> function is that it only tells you what's <em>installed</em>, not what has an <em>available license</em>. It's possible to have a toolbox installed and no license to use it (or all the available licenses could be checked out by other users). A better choice is the <a href="https://www.mathworks.com/help/matlab/ref/license.html" rel="nofollow noreferrer"><code>license</code></a> function, which (as you pointed out) requires a unique <a href="https://www.mathworks.com/help/matlab/ref/license.html#buk96bm-1-feature" rel="nofollow noreferrer">"feature string"</a> for each toolbox.</p> <p>Here's an older list of feature strings for various toolboxes taken from a now-defunct <a href="http://www.mathworks.co.uk/matlabcentral/newsreader/view_thread/244320" rel="nofollow noreferrer">newsgroup thread</a> (link is now dead):</p> <pre><code>featureStr = {'Aerospace_Blockset'; ... 'Aerospace_Toolbox'; ... 'Bioinformatics_Toolbox'; ... 'Communication_Blocks'; ... 'Communication_Toolbox'; ... 'Compiler'; ... 'Control_Toolbox'; ... 'Curve_Fitting_Toolbox'; ... 'Data_Acq_Toolbox'; ... 'Database_Toolbox'; ... 'Datafeed_Toolbox'; ... 'Dial_and_Gauge_Blocks'; ... 'Distrib_Computing_Toolbox'; ... 'Econometrics_Toolbox'; ... 'EDA_Simulator_Link_DS'; ... 'Embedded_Target_c166'; ... 'Embedded_Target_c2000'; ... 'Embedded_Target_c6000'; ... 'Embedded_Target_MPC555'; ... 'Excel_Link'; ... 'Filter_Design_HDL_Coder'; ... 'Filter_Design_Toolbox'; ... 'Fin_Derivatives_Toolbox'; ... 'Financial_Toolbox'; ... 'Fixed_Income_Toolbox'; ... 'Fixed_Point_Toolbox'; ... 'Fixed-Point_Blocks'; ... 'Fuzzy_Toolbox'; ... 'GADS_Toolbox'; ... 'IDE_Link_MU'; ... 'Identification_Toolbox'; ... 'Image_Acquisition_Toolbox'; ... 'Image_Toolbox'; ... 'Instr_Control_Toolbox'; ... 'Link_for_Incisive'; ... 'Link_for_ModelSim'; ... 'Link_for_Tasking'; ... 'Link_for_VisualDSP'; ... 'MAP_Toolbox'; ... 'MATLAB'; ... 'MATLAB_Builder_for_dot_Net'; ... 'MATLAB_Builder_for_Java'; ... 'MATLAB_Distrib_Comp_Engine'; ... 'MATLAB_Excel_Builder'; ... 'MATLAB_Link_for_CCS'; ... 'MATLAB_Report_Gen'; ... 'MBC_Toolbox'; ... 'MPC_Toolbox'; ... 'NCD_Toolbox'; ... 'Neural_Network_Toolbox'; ... 'OPC_Toolbox'; ... 'Optimization_Toolbox'; ... 'PDE_Toolbox'; ... 'Power_System_Blocks'; ... 'Real-Time_Win_Target'; ... 'Real-Time_Workshop'; ... 'RF_Blockset'; ... 'RF_Toolbox'; ... 'Robust_Toolbox'; ... 'RTW_Embedded_Coder'; ... 'Signal_Blocks'; ... 'Signal_Toolbox'; ... 'SimBiology'; ... 'SimDriveline'; ... 'SimElectronics'; ... 'SimEvents'; ... 'SimHydraulics'; ... 'SimMechanics'; ... 'Simscape'; ... 'SIMULINK'; ... 'Simulink_Control_Design'; ... 'Simulink_Design_Verifier'; ... 'Simulink_HDL_Coder'; ... 'Simulink_Param_Estimation'; ... 'SIMULINK_Report_Gen'; ... 'SL_Verification_Validation'; ... 'Spline_Toolbox'; ... 'Stateflow'; ... 'Stateflow_Coder'; ... 'Statistics_Toolbox'; ... 'Symbolic_Toolbox'; ... 'SystemTest'; ... 'Video_and_Image_Blockset'; ... 'Virtual_Reality_Toolbox'; ... 'Wavelet_Toolbox'; ... 'XPC_Embedded_Option'; ... 'XPC_Target'}; </code></pre> <p>This covers many of the common ones, but isn't exhaustive and doesn't include feature strings for newer toolboxes. There doesn't appear to be any readily-available list of current feature strings for all MathWorks toolboxes. I believe you can find them on the "INCREMENT" lines in a license file, or (<a href="https://stackoverflow.com/questions/2060382/how-would-one-check-for-installed-matlab-toolboxes-in-a-script-function/2061547#comment1995076_2061547">as vlee mentions in a comment</a>) you can call a function from a given toolbox and then use <code>license('inuse')</code> to get the feature string from the displayed list of toolboxes currently being used. However, both of the above options require an available license already.</p> <p>Using the above list of feature strings and the function <a href="https://www.mathworks.com/help/matlab/ref/license.html" rel="nofollow noreferrer"><code>license</code></a>, you can check which toolboxes you have a license to use. The following code checks for licenses for the entire list above:</p> <pre><code>index = cellfun(@(f) license('test', f), featureStr); availableFeatures = featureStr(logical(index)); </code></pre> <p>However, the above just confirms that the license <em>exists</em>, not that it can be <em>checked out</em>. The license could have expired or all the available licenses could be checked out by other users. To be absolutely certain that you will be able to use the available toolboxes, you can actually try to check out a license for the ones you need and test to see if you were successful. The following code attempts to check out a license for all the available toolboxes found above:</p> <pre><code>index = cellfun(@(f) license('checkout', f), availableFeatures); checkedOutFeatures = availableFeatures(logical(index)); </code></pre> <p><strong>WORD OF WARNING!:</strong></p> <p><a href="https://stackoverflow.com/questions/2060382/how-would-one-check-for-installed-matlab-toolboxes-in-a-script-function/2061547#comment1992534_2061547">As Jason S mentions in a comment below</a>, it's a bad idea to check out licenses willy-nilly, since they won't be released until you close MATLAB. <strong>You should only check out a license that you know you will need for a given application!</strong> Normally, licenses aren't checked out until you try to use a function from a given toolbox. For example:</p> <pre><code>&gt;&gt; license('inuse') matlab &gt;&gt; gaussFilter = fspecial('gaussian'); % An Image Processing Toolbox function &gt;&gt; license('inuse') image_toolbox matlab </code></pre>
1,510,869
Does the C preprocessor strip comments or expand macros first?
<p>Consider this (horrible, terrible, no good, very bad) code structure:</p> <pre><code>#define foo(x) // commented out debugging code // Misformatted to not obscure the point if (a) foo(a); bar(a); </code></pre> <p>I've seen two compilers' preprocessors generate different results on this code:</p> <pre><code>if (a) bar(a); </code></pre> <p>and</p> <pre><code>if (a) ; bar(a); </code></pre> <p>Obviously, this is a bad thing for a portable code base.</p> <p>My question: What is the preprocessor supposed to do with this? Elide comments first, or expand macros first?</p>
1,510,919
6
4
null
2009-10-02 17:26:58.87 UTC
6
2016-06-30 19:24:27.393 UTC
2016-06-30 19:24:27.393 UTC
null
3,204,551
null
90,002
null
1
63
c|comments|c-preprocessor|c99
30,791
<p>Unfortunately, the original <a href="http://eli-project.sourceforge.net/c_html/c.html" rel="noreferrer">ANSI C Specification</a> specifically excludes any Preprocessor features in section 4 ("This specification describes only the C language. It makes no provision for either the library or the preprocessor.").</p> <p>The <a href="http://www.open-std.org/JTC1/sc22/wg14/www/docs/n1124.pdf" rel="noreferrer">C99 specification</a> handles this explicity, though. The comments are replaced with a single space in the "translation phase", which happens prior to the Preprocessing directive parsing. (Section 6.10 for details).</p> <p><a href="http://msdn.microsoft.com/en-us/library/bxss3ska%28VS.71%29.aspx" rel="noreferrer">VC++</a> and the <a href="http://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html" rel="noreferrer">GNU C Compiler</a> both follow this paradigm - other compilers may not be compliant if they're older, but if it's C99 compliant, you should be safe.</p>
2,065,928
Maven 2 assembly with dependencies: jar under scope "system" not included
<p>I am using maven-assembly plugin to create a jar of my application, including its dependencies as follows:</p> <pre><code>&lt;assembly&gt; &lt;id&gt;macosx&lt;/id&gt; &lt;formats&gt; &lt;format&gt;tar.gz&lt;/format&gt; &lt;format&gt;dir&lt;/format&gt; &lt;/formats&gt; &lt;dependencySets&gt; &lt;dependencySet&gt; &lt;includes&gt; &lt;include&gt;*:jar&lt;/include&gt; &lt;/includes&gt; &lt;outputDirectory&gt;lib&lt;/outputDirectory&gt; &lt;/dependencySet&gt; &lt;/dependencySets&gt; &lt;/assembly&gt; </code></pre> <p>(I omitted some other stuff that is not related to the question)</p> <p>So far this has worked fine because it creates a <code>lib</code> directory with all dependencies. However, I recently added a new dependency whose scope is <code>system</code>, and it does not copy it to the <code>lib</code> output directory. i must be missing something basic here, so I call for help.</p> <p>The dependency that I just added is:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;sourceforge.jchart2d&lt;/groupId&gt; &lt;artifactId&gt;jchart2d&lt;/artifactId&gt; &lt;version&gt;3.1.0&lt;/version&gt; &lt;scope&gt;system&lt;/scope&gt; &lt;systemPath&gt;${project.basedir}/external/jchart2d-3.1.0.jar&lt;/systemPath&gt; &lt;/dependency&gt; </code></pre> <p>The only way I was able to include this dependency was by adding the following to the assembly element:</p> <pre><code>&lt;files&gt; &lt;file&gt; &lt;source&gt;external/jchart2d-3.1.0.jar&lt;/source&gt; &lt;outputDirectory&gt;lib&lt;/outputDirectory&gt; &lt;/file&gt; &lt;/files&gt; </code></pre> <p>However, this forces me to change the pom and the assembly file whenever this jar is renamed, if ever. Also, it seems just wrong.</p> <p>I have tried with <code>&lt;scope&gt;runtime&lt;/scope&gt;</code> in the <code>dependencySets</code> and <code>&lt;include&gt;sourceforge.jchart2d:jchart2d&lt;/include&gt;</code> with no luck.</p> <p>So how do you include a <code>system</code> scoped jar to your assembly file in maven 2?</p> <p>Thanks a lot</p>
2,068,101
7
2
null
2010-01-14 17:01:44.153 UTC
34
2019-12-11 16:20:28.36 UTC
null
null
null
null
227,103
null
1
68
maven-2|maven-plugin|maven-assembly-plugin
78,808
<p>I'm not surprised that system scope dependencies are not added (after all, dependencies with a system scope must be explicitly provided by definition). Actually, if you really don't want to put that dependency in your local repository (for example because you want to distribute it as part of your project), this is what I would do:</p> <ul> <li>I would put the dependency in a "file system repository" local to the project.</li> <li><p>I would declare that repository in my <code>pom.xml</code> like this:</p> <pre><code>&lt;repositories&gt; &lt;repository&gt; &lt;id&gt;my&lt;/id&gt; &lt;url&gt;file://${basedir}/my-repo&lt;/url&gt; &lt;/repository&gt; &lt;/repositories&gt; </code></pre></li> <li><p>I would just declare the artifact without the <code>system</code> scope, this is just a source of troubles:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;sourceforge.jchart2d&lt;/groupId&gt; &lt;artifactId&gt;jchart2d&lt;/artifactId&gt; &lt;version&gt;3.1.0&lt;/version&gt; &lt;/dependency&gt; </code></pre></li> </ul> <p>I'm not 100% sure this will suit your needs but I think it's a better solution than using the system scope.</p> <p><strong>Update:</strong> I should have mentioned that in my original answer and I'm fixing it now. To install a third party library in the file-based repository, use <code>install:install-file</code> with the <a href="http://maven.apache.org/plugins/maven-install-plugin/install-file-mojo.html#localRepositoryPath" rel="noreferrer"><code>localRepositoryPath</code></a> parameter:</p> <pre><code>mvn install:install-file -Dfile=&lt;path-to-file&gt; \ -DgroupId=&lt;myGroup&gt; \ -DartifactId=&lt;myArtifactId&gt; \ -Dversion=&lt;myVersion&gt; \ -Dpackaging=&lt;myPackaging&gt; \ -DlocalRepositoryPath=&lt;path-to-my-repo&gt; </code></pre> <p>You can paste this as is in a *nix shell. On windows, remove the "<code>\</code>" and put everything on a single line.</p>
1,432,961
How do I make HttpURLConnection use a proxy?
<p>If I do this...</p> <pre><code>conn = new URL(urlString).openConnection(); System.out.println("Proxy? " + conn.usingProxy()); </code></pre> <p>it prints</p> <pre><code>Proxy? false </code></pre> <p>The problem is, I am behind a proxy. Where does the JVM get its proxy information from on Windows? How do I set this up? All my other apps seem perfectly happy with my proxy.</p>
1,433,296
7
0
null
2009-09-16 13:28:16.973 UTC
58
2021-09-03 23:52:17.063 UTC
null
null
null
null
974
null
1
157
java|windows|http|proxy
299,975
<p>Since java 1.5 you can also pass a <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/net/Proxy.html" rel="noreferrer">java.net.Proxy</a> instance to the <a href="http://docs.oracle.com/javase/7/docs/api/java/net/URL.html#openConnection%28java.net.Proxy%29" rel="noreferrer"><code>openConnection(proxy)</code></a> method:</p> <pre><code>//Proxy instance, proxy ip = 10.0.0.1 with port 8080 Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080)); conn = new URL(urlString).openConnection(proxy); </code></pre> <p>If your proxy requires authentication it will give you response 407.</p> <p>In this case you'll need the following code:</p> <pre><code> Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return (new PasswordAuthentication("user", "password".toCharArray())); } }; Authenticator.setDefault(authenticator); </code></pre>
1,414,769
Turn off Visual Studio Attach security warning when debugging IIS
<p>When using Visual Studio 2008 or 2010, every time you attach to IIS w3wp.exe you get the Attach Security Warning:</p> <p><a href="https://i.stack.imgur.com/ENVEG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ENVEGm.png" alt="Attach Security Warning" /></a></p> <p>How do you turn this of?</p> <p>It would be cool to know also, how to keep it attached for longer, as this seems to time out after a while.</p> <p>Also, I've tried the Microsoft Docs page <a href="https://docs.microsoft.com/en-us/visualstudio/debugger/security-warning-attaching-to-a-process-owned-by-an-untrusted-user" rel="nofollow noreferrer">Security Warning: Attaching to a process owned by an untrusted user can be dangerous</a>, but it didn't work</p>
2,026,878
11
1
null
2009-09-12 09:59:33.393 UTC
46
2022-02-09 13:21:24.927 UTC
2022-02-09 13:21:24.927 UTC
null
1,366,033
null
162,325
null
1
164
visual-studio-2010|visual-studio|visual-studio-2008|iis|iis-7
37,842
<p>Also found in the article mentioned by Tzury, but to sum up the answers in this thread:</p> <p><strong>Make sure Visual Studio is not running when changing the registry key or it will be overwritten on exit with the old value</strong></p> <p><strong>Visual Studio 2022</strong>: Follow <a href="https://www.davici.nl/blog/disable-visual-studio-2022-iis-security-attach-warning" rel="noreferrer">these instructions</a>, then reboot.<br /> <strong>Visual Studio 2019</strong>: Follow <a href="https://www.davici.nl/blog/disable-visual-studio-2019-iis-security-attach-warning" rel="noreferrer">these instructions</a>, then reboot.</p> <p>For older versions of Visual Studio:</p> <p>Change (or create) the following registry key to <strong>1</strong>:</p> <p><strong>Visual Studio 2008</strong> <code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Debugger\DisableAttachSecurityWarning</code></p> <p><strong>Visual Studio 2010</strong> <code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Debugger\DisableAttachSecurityWarning</code></p> <p><strong>Visual Studio 2012</strong> <code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\Debugger\DisableAttachSecurityWarning</code></p> <p><strong>Visual Studio 2013</strong> <code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\12.0\Debugger\DisableAttachSecurityWarning</code></p> <p><strong>Visual Studio 2015</strong> <code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\14.0\Debugger\DisableAttachSecurityWarning</code></p> <p>For VS2015, you might need to create the Registry Key referenced above.</p> <ol> <li>Make sure Visual Studio is not running, and open the Registry Editor.</li> <li>Navigate to <code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\14.0\Debugger</code>, right-click and create a new <code>DWORD</code>:</li> </ol> <ul> <li>Name: <code>DisableAttachSecurityWarning</code></li> <li>Value: <code>1</code>.</li> </ul> <p><strong>Update:</strong> If you don't want to open up regedit, save this <a href="https://gist.githubusercontent.com/zidad/418e0ac6f670f2b0e14f/raw/324cf866f6dabcf3021fd908447a430803bf6609/disable-attach-security-warning.reg" rel="noreferrer" title="disable-attach-security-warning.reg">gist</a> as a *.reg file and run it (imports the keys for all VS versions lower than VS2017).</p> <p><strong>Visual Studio 2017</strong></p> <p>The configuration is saved in a private registry location, see this answer: <a href="https://stackoverflow.com/a/41122603/67910">https://stackoverflow.com/a/41122603/67910</a></p> <p>For <strong>VS 2017</strong>, save this <a href="https://gist.githubusercontent.com/hmoratopcs/f7461c95ccdcad7bcbc3686bd45cec84/raw/0d34eb734d088455b854d3b415abd94446dfb05d/DisableAttachSecurityWarningVS2017.ps1" rel="noreferrer" title="DisableAttachSecurityWarningVS2017.ps1">gist</a> as a *.ps1 file and run it as admin, or copy and paste the following code in a ps1 file:</p> <pre class="lang-cs prettyprint-override"><code>#IMPORTANT: Must be run as admin dir $env:LOCALAPPDATA\Microsoft\VisualStudio\15.* | % { #https://stackoverflow.com/a/41122603 New-PSDrive HKU Registry HKEY_USERS reg load 'HKU\VS2017PrivateRegistry\' $_\privateregistry.bin $BasePath='HKU:\VS2017PrivateRegistry\Software\Microsoft\VisualStudio' $keysResult=dir $BasePath $keysResult | ? {$_.Name -match '\\\d+\.\d+_[^_]+$'} | % { $keyName = $_.Name -replace 'HKEY_USERS','HKU:' New-ItemProperty -Path $keyName\Debugger -Name DisableAttachSecurityWarning -Value 1 } $keysResult.Handle.Close() [gc]::collect() reg unload 'HKU\VS2017PrivateRegistry' Remove-PSDrive HKU } </code></pre>
1,625,249
Android: How to bind spinner to custom object list?
<p>In the user interface there has to be a spinner which contains some names (the names are visible) and each name has its own ID (the IDs are not equal to display sequence). When the user selects the name from the list the variable currentID has to be changed.</p> <p>The application contains the ArrayList</p> <p>Where User is an object with ID and name:</p> <pre><code>public class User{ public int ID; public String name; } </code></pre> <p>What I don't know is how to create a spinner which displays the list of user's names and bind spinner items to IDs so when the spinner item is selected/changed the variable currentID is set to appropriate value.</p> <p>I would appreciate if anyone could show the solution of the described problem or provide any link useful to solve the problem.</p> <p>Thanks!</p>
1,626,016
17
0
null
2009-10-26 14:45:09.143 UTC
65
2021-06-29 07:24:41.383 UTC
null
null
null
null
22,996
null
1
150
android|adapter|spinner
246,019
<p>You can <a href="https://stackoverflow.com/questions/1587028/android-configure-spinner-to-use-array">look at this answer</a>. You can also go with a custom adapter, but the solution below is fine for simple cases.</p> <p>Here's a re-post:</p> <p>So if you came here because you want to have both labels and values in the Spinner - here's how I did it:</p> <ol> <li>Just create your <code>Spinner</code> the usual way</li> <li>Define 2 equal size arrays in your <code>array.xml</code> file -- one array for labels, one array for values</li> <li>Set your <code>Spinner</code> with <code>android:entries="@array/labels"</code> </li> <li><p>When you need a value, do something like this (no, you don't have to chain it): </p> <pre><code> String selectedVal = getResources().getStringArray(R.array.values)[spinner.getSelectedItemPosition()]; </code></pre></li> </ol>
1,749,966
C# - how to determine whether a Type is a number
<p>Is there a way to determine whether or not a given .Net Type is a number? For example: <code>System.UInt32/UInt16/Double</code> are all numbers. I want to avoid a long switch-case on the <code>Type.FullName</code>.</p>
1,750,024
21
2
null
2009-11-17 16:15:04.82 UTC
27
2022-09-22 20:07:44.7 UTC
2019-01-19 22:31:47.043 UTC
null
4,574
null
55,373
null
1
134
c#|.net|types
111,689
<p><strike>Try this:</p> <pre><code>Type type = object.GetType(); bool isNumber = (type.IsPrimitiveImple &amp;&amp; type != typeof(bool) &amp;&amp; type != typeof(char)); </code></pre> <blockquote> <p>The primitive types are Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Char, Double,and Single. </strike></p> </blockquote> <p>Taking <a href="https://stackoverflow.com/questions/1749966/c-how-to-determine-whether-a-type-is-a-number/1750093#1750093">Guillaume's solution</a> a little further:</p> <pre><code>public static bool IsNumericType(this object o) { switch (Type.GetTypeCode(o.GetType())) { case TypeCode.Byte: case TypeCode.SByte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Decimal: case TypeCode.Double: case TypeCode.Single: return true; default: return false; } } </code></pre> <p>Usage:</p> <pre><code>int i = 32; i.IsNumericType(); // True string s = "Hello World"; s.IsNumericType(); // False </code></pre>
41,900,387
Mapping column names to random forest feature importances
<p>I am trying to plot feature importances for a random forest model and map each feature importance back to the original coefficient. I've managed to create a plot that shows the importances and uses the original variable names as labels but right now it's ordering the variable names in the order they were in the dataset (and not by order of importance). How do I order them in order of feature importance? Thanks!</p> <p><a href="https://i.stack.imgur.com/b2cop.png" rel="noreferrer"><img src="https://i.stack.imgur.com/b2cop.png" alt="enter image description here"></a></p> <p>My code is:</p> <pre><code>importances = brf.feature_importances_ std = np.std([tree.feature_importances_ for tree in brf.estimators_], axis=0) indices = np.argsort(importances)[::-1] # Print the feature ranking print("Feature ranking:") for f in range(x_dummies.shape[1]): print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]])) # Plot the feature importances of the forest plt.figure(figsize=(8,8)) plt.title("Feature importances") plt.bar(range(x_train.shape[1]), importances[indices], color="r", yerr=std[indices], align="center") feature_names = x_dummies.columns plt.xticks(range(x_dummies.shape[1]), feature_names) plt.xticks(rotation=90) plt.xlim([-1, x_dummies.shape[1]]) plt.show() </code></pre>
41,900,730
4
4
null
2017-01-27 18:09:10.027 UTC
10
2020-01-03 04:58:07.153 UTC
2017-01-27 18:25:03.627 UTC
null
7,117,564
null
7,117,564
null
1
15
python|pandas
36,206
<p>A sort of generic solution would be to throw the features/importances into a dataframe and sort them before plotting:</p> <pre><code>import pandas as pd %matplotlib inline #do code to support model #"data" is the X dataframe and model is the SKlearn object feats = {} # a dict to hold feature_name: feature_importance for feature, importance in zip(data.columns, model.feature_importances_): feats[feature] = importance #add the name/value pair importances = pd.DataFrame.from_dict(feats, orient='index').rename(columns={0: 'Gini-importance'}) importances.sort_values(by='Gini-importance').plot(kind='bar', rot=45) </code></pre>
6,399,898
Is the typedef-name optional in a typedef declaration?
<p>I was quite surprised when I saw the following code compile without errors or warnings in g++-4.2:</p> <pre><code>typedef enum test { one }; </code></pre> <p>My assumption was that if you used the <code>typedef</code> keyword it would require an extra identifier as in:</p> <pre><code>typedef enum test { one } test; </code></pre> <p>As already mentioned, g++-4.2 accepts it without even a warning. Clang++ 3.0 warns "<em>warning: typedef requires a name</em>", similarly Comeau warns "<em>warning: declaration requires a typedef name</em>", and g++-4.6 informs: "<em>warning: 'typedef' was ignored in this declaration</em>".</p> <p>I have not been able to identify where in the standard this is allowed, and I find it slightly confusing that two of the compilers warn that it is <em>required</em>, shouldn't it be an error if the typedef-name is <em>required</em> but not present?</p> <p><strong>UPDATE</strong>: I have checked in C with the same compilers. Clang and comeau yield the same output, gcc gives a warning: "<em>warning: useless storage class specifier in empty declaration</em>", which seems even more confusing.</p> <p><strong>UPDATE</strong>: I have checked removing the name of the enum and the results are the same:</p> <pre><code>typedef enum { one }; </code></pre> <p>Similarly with a named struct:</p> <pre><code>typedef struct named { int x }; </code></pre> <p>But not with an unnamed struct, in which case the code was rejected in g++ (4.2/4.6) with "<em>error: missing type-name in typedef-declaration</em>", gcc (4.2/4.6) gave a warning: "<em>warning: unnamed struct/union that defines no instances</em>", clang++ "<em>warning: declaration does not declare anything</em>", comeau "<em>error: declaration requires a typedef name</em>"</p>
6,399,998
3
7
null
2011-06-19 00:56:47.123 UTC
9
2011-06-19 10:38:26.72 UTC
2011-06-19 01:30:07.96 UTC
null
36,565
null
36,565
null
1
36
c++|c|typedef
38,673
<p>It is a degenerate syntax that is allowed but provides no benefit. Most modern compilers can be provoked into emitting a warning about it; by default, they may not. Without the typedef name, the keyword <code>typedef</code> is superfluous; in your example, it is completely equivalent to:</p> <pre><code>enum test { one }; </code></pre> <p>Another place where it can occur is with a structure:</p> <pre><code>typedef struct SomeThing { int whatever; }; </code></pre> <p>This is equivalent to:</p> <pre><code>struct SomeThing { int whatever; }; </code></pre> <p>Note that <code>typedef</code> is officially (or syntactically) a 'storage class specifier', like <code>static</code>, <code>extern</code>, <code>auto</code> and <code>register</code>.</p> <hr> <h2>C Standard</h2> <p>In ISO/IEC 9899:1999 (that's the C standard), we find:</p> <blockquote> <h3>§6.7 Declarations</h3> <p><strong>Syntax</strong></p> <p><em>declaration</em>:</p> <p><code></code> <em>declaration-specifiers</em> <i>init-declarator-list</i><sub>opt</sub>;</p> <p><em>declaration-specifiers</em>:</p> <p><code></code> <em>storage-class-specifier</em> <i>declaration-specifiers</i><sub>opt</sub></p> <p><code></code> <em>type-specifier</em> <i>declaration-specifiers</i><sub>opt</sub></p> <p><code></code> <em>type-qualifier</em> <i>declaration-specifiers</i><sub>opt</sub></p> <p><code></code> <em>function-specifier</em> <i>declaration-specifiers</i><sub>opt</sub></p> <p><em>init-declarator-list</em>:</p> <p><code></code> <em>init-declarator</em></p> <p><code></code> <em>init-declarator-list</em> , <em>init-declarator</em></p> <p><em>init-declarator</em>:</p> <p><code></code> <em>declarator</em></p> <p><code></code> <em>declarator</em> = <em>initializer</em></p> </blockquote> <p>And (as requested):</p> <blockquote> <h3>§6.7.1 Storage-class specifiers</h3> <p><strong>Syntax</strong></p> <p>storage-class-specifier:</p> <p><code>typedef</code></p> <p><code>extern</code></p> <p><code>static</code></p> <p><code>auto</code></p> <p><code>register</code></p> </blockquote> <p>If you track through that syntax, there are a lot of degenerate possibilities, and what you showed is just one of the many.</p> <hr> <h2>C++ Standard</h2> <p>It is possible that C++ has different rules.</p> <p>In ISO/IEC 14882:1998 (the original C++ standard), we find in §7.1.1 'Storage class specifiers' that C++ does not treat <code>typedef</code> as a storage class; the list adds <code>mutable</code> and excludes <code>typedef</code>. So, the grammatical specification of <code>typedef</code> in C++ is definitely different from the C specification.</p> <blockquote> <h3>§7 Declarations</h3> </blockquote> <p>Declarations specify how names are to be interpreted. Declarations have the form</p> <blockquote> <p>declaration-seq:</p> <p><code></code> declaration</p> <p><code></code> declaration-seq declaration</p> <p>declaration:</p> <p><code></code> block-declaration</p> <p><code></code> function-definition</p> <p><code></code> template-declaration</p> <p><code></code> explicit-instantiation</p> <p><code></code> explicit-specialization</p> <p><code></code> linkage-specification</p> <p><code></code> namespace-definition</p> <p>block-declaration:</p> <p><code></code> simple-declaration</p> <p><code></code> asm-definition</p> <p><code></code> namespace-alias-definition</p> <p><code></code> using-declaration</p> <p><code></code> using-directive</p> <p>simple-declaration:</p> <p><code></code> decl-specifier-seq<sub>opt</sub> init-declarator-list<sub>opt</sub> ;</p> <p>...</p> <p>¶5 If the decl-specifier-seq contains the <code>typedef</code> specifier, the declaration is called a <code>typedef</code> declaration and the name of each <code>init-declarator</code> is declared to be a typedef-name, synonymous with its associated type (7.1.3).</p> <h3>§7.1 Specifiers [dcl.spec]</h3> <p>The specifiers that can be used in a declaration are</p> <p>decl-specifier:</p> <p><code></code> storage-class-specifier</p> <p><code></code> type-specifier</p> <p><code></code> function-specifier</p> <p><code></code> <code>friend</code></p> <p><code></code> <code>typedef</code></p> <p>decl-specifier-seq:</p> <p><code></code> decl-specifier-seq<sub>opt</sub></p> <p><code></code> decl-specifier</p> <h3>§7.1.1 Storage class specifiers [dcl.stc]</h3> <p>storage-class-specifier:</p> <p><code>auto</code></p> <p><code>register</code></p> <p><code>static</code></p> <p><code>extern</code></p> <p><code>mutable</code></p> <h3>§7.1.2 Function specifiers [dcl.fct.spec]</h3> <p>function-specifier:</p> <p><code>inline</code></p> <p><code>virtual</code></p> <p><code>explicit</code></p> <h3>§7.1.3 The typedef specifier [dcl.typedef]</h3> <p>Declarations containing the decl-specifier <code>typedef</code> declare identifiers that can be used later for naming fundamental (3.9.1) or compound (3.9.2) types. The <code>typedef</code> specifier shall not be used in a function-definition (8.4), and it shall not be combined in a decl-specifier-seq with any other kind of specifier except a type-specifier.</p> <p>typedef-name:</p> <p><code></code> identifier</p> <p>...</p> <p>In a given scope, a typedef specifier can be used to redefine the name of any type declared in that scope to refer to the type to which it already refers. [Example:</p> <pre><code>typedef struct s { /* ... */ } s; typedef int I; typedef int I; typedef I I; </code></pre> <p>—end example]</p> <h3>§7.1.4 The friend specifier [dcl.friend]</h3> <p>The friend specifier is used to specify access to class members; see 11.4.</p> <h3>§7.1.5 Type specifiers [dcl.type]</h3> <p>type-specifier:</p> <p><code></code> simple-type-specifier</p> <p><code></code> class-specifier</p> <p><code></code> enum-specifier</p> <p><code></code> elaborated-type-specifier</p> <p><code></code> cv-qualifier</p> </blockquote> <hr> <p>Since §7 ¶5 says that <code>typedef</code> names come from the <em>init-declarator</em> and the <em>init-declarator-list</em> is tagged '<em>opt</em>', I think that means that the <code>typedef</code> name can be omitted in C++, just as in C.</p>
6,434,865
Passing an object to HTML attributes
<p>How to pass an object to HTML attributes? For example I have the following code:</p> <pre><code>var attrs = new { id = "myid", style = "color: Red;" }; </code></pre> <p>How to convert attrs to string like this to embed them into an HTML markup: </p> <pre><code>id="myid" style="color: Red;" </code></pre> <p>Thanks in advance :)</p>
6,434,991
3
1
null
2011-06-22 04:22:10.787 UTC
13
2014-08-22 14:33:45.437 UTC
2013-07-11 10:18:31.323 UTC
null
930,252
null
463,650
null
1
43
c#|asp.net|html|asp.net-mvc-3
59,826
<p>This functionality is, surprisingly enough, provided by the <a href="http://msdn.microsoft.com/en-us/library/system.web.routing.routevaluedictionary.aspx"><code>RouteValueDictionary</code></a> class:</p> <pre><code>IDictionary&lt;string, object&gt; htmlAttributes = new RouteValueDictionary(attrs); </code></pre> <p>You can then use this dictionary in conjunction with a <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.tagbuilder.aspx"><code>TagBuilder</code></a>, which you will probably be using anyway:</p> <pre><code>var tagBuilder = new TagBuilder("input"); tagBuilder.MergeAttributes(htmlAttributes); tagBuilder.ToString(TagRenderMode.Normal); </code></pre> <p>You can see this done in the ASP.NET MVC source code itself; one of the simpler examples is in <a href="https://github.com/mono/aspnetwebstack/blob/1ccfcdfc11da19a88f6efc6f512e67b68fa04fec/src/System.Web.Mvc/Html/TextAreaExtensions.cs#L158-L191">TextAreaExtensions.cs</a>.</p> <p><strong>EDIT:</strong></p> <p>In order to properly convert "data_attr" to "data-attr", use the <code>AnonymousObjectToHtmlAttributes</code> static method.</p> <pre><code>IDictionary&lt;string, object&gt; htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(attrs); </code></pre>
23,689,647
How do I replace <NA> values with zeros in R?
<p>I have a data.frame and some columns have <code>NA</code> values. I want to replace the <code>&lt;NA&gt;</code>s with zeros. How I do this?</p> <p>Actually, mydate, shown here, isn't my original data. the original is too large to show here. </p> <pre><code>mydata = read.spss('mydata.sav', use.value.labels = TRUE, to.data.frame = TRUE, max.value.labels = Inf, trim.factor.names = FALSE, trim_values = FALSE, reencode = "UTF-8") &gt; mydata Q_16_O3 Q_16_O4 Q_16_O5 Q_16_O6 Q_16_O7 Q_16_O8 Q_16_O9 10 &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; 11 &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; 12 &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; 13 &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; 14 &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; 15 Trem &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; 16 &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; 17 &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; 18 &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; 19 &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; 20 &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; str(mydata) 'data.frame': 11 obs. of 7 variables: $ Q_16_O3: Factor w/ 10 levels "Ônibus","Vans",..: NA NA NA NA NA 4 NA NA NA NA ... $ Q_16_O4: Factor w/ 10 levels "Ônibus","Vans",..: NA NA NA NA NA NA NA NA NA NA ... $ Q_16_O5: Factor w/ 10 levels "Ônibus","Vans",..: NA NA NA NA NA NA NA NA NA NA ... $ Q_16_O6: Factor w/ 10 levels "Ônibus","Vans",..: NA NA NA NA NA NA NA NA NA NA ... $ Q_16_O7: Factor w/ 10 levels "Ônibus","Vans",..: NA NA NA NA NA NA NA NA NA NA ... $ Q_16_O8: Factor w/ 10 levels "Ônibus","Vans",..: NA NA NA NA NA NA NA NA NA NA ... $ Q_16_O9: Factor w/ 10 levels "Ônibus","Vans",..: NA NA NA NA NA NA NA NA NA NA ... </code></pre> <p>I would like to use the freq function, so I must not change its structure(mydata). </p> <p>ps: My problem is <code>&lt;NA&gt;</code>, not <code>NA</code> In the <code>NA</code> case, I have a solution <a href="https://stackoverflow.com/questions/8161836/how-do-i-replace-na-values-with-zeros-in-r/8166616#8166616">HERE</a>.</p>
23,689,782
1
3
null
2014-05-15 22:19:48.417 UTC
3
2016-07-13 09:15:25.423 UTC
2016-07-13 09:15:25.423 UTC
null
1,505,504
null
3,642,673
null
1
5
r|import
52,952
<p>For practically any data structure <code>X</code> containing numerics, use </p> <pre><code>X[is.na(X)] &lt;- 0 </code></pre> <p>Your question seems slightly discombobulated though - you have indicated that you mean <code>&lt;NA&gt;</code> not NA, without explaining what <em>type</em> <code>&lt;NA&gt;</code> is.</p> <p>If it is the string <code>"&lt;NA&gt;"</code> you mean, then</p> <pre><code>X[X=="&lt;NA&gt;"] &lt;- "0" </code></pre> <p>If you have mixed data types in your data frame, check for that too:</p> <pre><code>X[is.character(X) &amp; X=="&lt;NA&gt;"] &lt;- "0" </code></pre> <p>which is strictly more useful in the numeric case.</p> <pre><code>X[is.numeric(X) &amp; is.na(X)] &lt;- 0 </code></pre> <p>This is a very common idiom for dealing with missing data in R, although you should also look at the parameter <code>na.rm = TRUE</code> which many functions such as <code>mean</code>, <code>sum</code>, &amp;c. will accept.</p> <p>This strategy will fail for a factor, because you cannot add new factor levels by assigning to the value of a factor. I haven't used read.spss, but looking at the <a href="http://stat.ethz.ch/R-manual/R-devel/library/foreign/html/read.spss.html" rel="noreferrer">documentation</a>, I suggest you add the <code>use.value.labels = FALSE</code> argument to your call, to avoid creating factors in the first place.</p> <p>In your specific case, your entire data frame is of the same type (factor). This means it's safe to convert to a character matrix</p> <pre><code>&gt; class(mydata[[1]]) "factor" &gt; mydataM &lt;- as.matrix(mydata) &gt; mode(mydataM) "character" </code></pre> <p>Now you can replace the NA values</p> <pre><code>X[is.character(X) &amp; X=="&lt;NA&gt;"] &lt;- "0" </code></pre> <p>In the more general case where you have unwanted factor columns mixed in with other types, you need to do something a little more complex.</p> <pre><code>myDataM=as.data.frame(lapply(x, function(x)if(class(x)=="factor")as.character(x)else x)) </code></pre>
15,934,724
FieldSet background color
<p>I am trying to set a background color for a fieldset in Telerik with the below code. </p> <p>Can someone point me in right direction, or have any other ideas?</p> <pre><code>.RadForm_Office2007.rfdFieldset fieldset { border: solid 1px #080808; background-color:yellow !important; } &lt;telerik:RadFormDecorator ID="RadFormDecorator1" runat="server" DecoratedControls="Fieldset" Skin="Office2007"/&gt; &lt;fieldset style="float: left; width: 280px;"&gt; &lt;legend&gt;Grid &lt;/legend&gt; &lt;telerik:RadTextBox runat="server"&gt;&lt;/telerik:RadTextBox&gt; &lt;/fieldset&gt; </code></pre>
15,934,784
2
0
null
2013-04-10 19:29:45.767 UTC
null
2020-11-27 11:00:50.063 UTC
2019-09-18 20:36:42.01 UTC
null
6,495,157
null
1,046,415
null
1
3
css|telerik|form-designer
39,667
<p>You can set the background color as</p> <pre><code>&lt;fieldset style="float: left; width: 280px; background-color:red;"&gt; </code></pre> <p>you can use color codes for setting background color like this</p> <pre><code>&lt;fieldset style="float: left; width: 280px; background-color:#999999;"&gt; </code></pre> <p>you can visit <a href="http://www.colorpicker.com/" rel="nofollow noreferrer">http://www.colorpicker.com/</a> for finding color codes</p>
16,043,140
ProgressDialog: change text size
<p>I create a ProgressDialog from java code:</p> <pre><code>mProgressDialog = ProgressDialog.show(this, ..., ... , true); </code></pre> <p>I want to change the message text size and its color how can I do it?</p>
16,045,641
3
0
null
2013-04-16 17:16:16.837 UTC
10
2015-10-26 07:46:53.16 UTC
null
null
null
null
2,064,262
null
1
9
android
13,075
<p>You can use a spannable string and set the color and size for the spannable string. Use the spannable string to set text color and size.</p> <p><strong>Note</strong>: Make sure the font size is not too large to fit in the screen</p> <p>activity_main.xml </p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" &gt; &lt;Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:layout_marginBottom="35dp" android:layout_marginLeft="56dp" android:text="Button" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>MainActivity</p> <pre><code> public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button b= (Button) findViewById(R.id.button1); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub String s= "Hello"; String title="MyTitle"; SpannableString ss1= new SpannableString(title); ss1.setSpan(new RelativeSizeSpan(2f), 0, ss1.length(), 0); ss1.setSpan(new ForegroundColorSpan(Color.RED), 0, ss1.length(), 0); SpannableString ss2= new SpannableString(s); ss2.setSpan(new RelativeSizeSpan(2f), 0, ss2.length(), 0); ss2.setSpan(new ForegroundColorSpan(Color.GREEN), 0, ss2.length(), 0); ProgressDialog pd = new ProgressDialog(MainActivity.this); pd.setTitle(ss1); pd.setMessage(ss2); pd.show(); } }); } } </code></pre> <p><img src="https://i.stack.imgur.com/B1y7j.png" alt="enter image description here"></p> <p><strong>OR</strong></p> <p>You can change the color of the the text by using a custom style</p> <p>styles.xml</p> <pre><code> &lt;style name="NewDialog" parent="@android:style/Theme.Dialog"&gt; &lt;item name="android:windowFrame"&gt;@null&lt;/item&gt; &lt;item name="android:windowBackground"&gt;@android:color/transparent&lt;/item&gt; &lt;item name="android:windowIsFloating"&gt;true&lt;/item&gt; &lt;item name="android:windowContentOverlay"&gt;@null&lt;/item&gt; &lt;item name="android:windowTitleStyle"&gt;@null&lt;/item&gt; &lt;item name="android:colorBackground"&gt;#ffffff&lt;/item&gt;// change background color &lt;item name="android:windowAnimationStyle"&gt;@android:style/Animation.Dialog&lt;/item&gt; &lt;item name="android:windowSoftInputMode"&gt;stateUnspecified|adjustPan&lt;/item&gt; &lt;item name="android:backgroundDimEnabled"&gt;true&lt;/item&gt; &lt;item name="android:width"&gt;600dip&lt;/item&gt; &lt;item name="android:height"&gt;100dip&lt;/item&gt; &lt;item name="android:textColor"&gt;#0FECFF&lt;/item&gt;// change color &lt;/style&gt; </code></pre> <p>In your activity</p> <pre><code> ProgressDialog pd = new ProgressDialog(this,R.style.NewDialog); </code></pre>
1,115,876
Autocompletion in Vim
<p>In a nutshell, I'm searching for a <strong>working</strong> autocompletion feature for the Vim editor. I've <a href="https://stackoverflow.com/questions/24109/c-ide-for-linux/24119#24119">argued before</a> that Vim completely replaces an IDE under Linux and while that's certainly true, it lacks one important feature: autocompletion.</p> <p>I know about <kbd>Ctrl</kbd>+<kbd>N</kbd>, <a href="http://ctags.sourceforge.net/" rel="noreferrer">Exuberant Ctags integration</a>, <a href="http://vim-taglist.sourceforge.net/" rel="noreferrer">Taglist</a>, <a href="http://www.vim.org/scripts/script.php?script_id=527" rel="noreferrer">cppcomplete</a> and <a href="http://www.vim.org/scripts/script.php?script_id=1520" rel="noreferrer">OmniCppComplete</a>. Alas, none of these fits my description of “working autocompletion:”</p> <ul> <li><strong><kbd>Ctrl</kbd>+<kbd>N</kbd></strong> works nicely (only) if you've forgotton how to spell <code>class</code>, or <code>while</code>. Oh well.</li> <li><strong>Ctags</strong> gives you the rudiments but has a lot of drawbacks.</li> <li><strong>Taglist</strong> is just a Ctags wrapper and as such, inherits most of its drawbacks (although it works well for <em>listing</em> declarations).</li> <li><strong>cppcomplete</strong> simply doesn't work as promised, and I can't figure out what I did wrong, or if it's “working” correctly and the limitations are by design.</li> <li><strong>OmniCppComplete</strong> seems to have the same problems as cppcomplete, i.e. auto-completion doesn't work properly. Additionally, the <code>tags</code> file once again needs to be updated manually.</li> </ul> <p>I'm aware of the fact that not even modern, full-blown IDEs offer good C++ code completion. That's why I've accepted Vim's lack in this area until now. But I think a fundamental level of code completion isn't too much to ask, and is in fact required for productive usage. So I'm searching for something that can accomplish at least the following things.</p> <ul> <li><p><strong>Syntax awareness</strong>. cppcomplete promises (but doesn't deliver for me), correct, scope-aware auto-completion of the following:</p> <pre><code>variableName.abc variableName-&gt;abc typeName::abc </code></pre> <p>And really, anything else is completely useless.</p></li> <li><p><strong>Configurability</strong>. I need to specify (easily) where the source files are, and hence where the script gets its auto-completion information from. In fact, I've got a Makefile in my directory which specifies the required include paths. Eclipse can interpret the information found therein, why not a Vim script as well?</p></li> <li><p><strong>Up-to-dateness</strong>. As soon as I change something in my file, I want the auto-completion to reflect this. I do <em>not</em> want to manually trigger <code>ctags</code> (or something comparable). Also, changes should be <em>incremental</em>, i.e. when I've changed just one file it's completely <em>unacceptable</em> for <code>ctags</code> to re-parse the whole directory tree (which may be huge).</p></li> </ul> <p>Did I forget anything? Feel free to update.</p> <p>I'm comfortable with quite a lot of configuration and/or tinkering but I don't want to program a solution from scratch, and I'm not good at debugging Vim scripts.</p> <p>A final note, I'd really like something similar for Java and C# but I guess that's too much to hope for: <code>ctags</code> only parses code files and both Java and C# have huge, precompiled frameworks that would need to be indexed. Unfortunately, <a href="http://greengoo.de/243/developing-dotnet-without-an-ide" rel="noreferrer">developing .NET without an IDE</a> is even more of a PITA than C++.</p>
14,764,809
7
5
null
2009-07-12 11:38:19.04 UTC
134
2019-09-19 18:17:45.227 UTC
2017-05-23 11:55:19.593 UTC
null
-1
null
1,968
null
1
263
c++|vim|ide|autocomplete
123,312
<p>Try <a href="https://github.com/ycm-core/YouCompleteMe" rel="noreferrer">YouCompleteMe</a>. It uses Clang through the libclang interface, offering semantic C/C++/Objective-C completion. It's much like clang_complete, but substantially faster and with fuzzy-matching.</p> <p>In addition to the above, YCM also provides semantic completion for C#, Python, Go, TypeScript etc. It also provides non-semantic, identifier-based completion for languages for which it doesn't have semantic support.</p>
1,116,116
Major game components
<p>I am in the process of developping a game, and after two months of work (not full time mind you), I have come to realise that our specs for the game are lacking a lot of details. I am not a professional game developper, this is only a hobby.</p> <p>What I would like to receive help or advices for is this: <strong>What are the major components that you find in games, that have to be developped or already exists as librairies?</strong> The objective of this question is for me to be able to specify more game aspects.</p> <p>Currently, we had specified pretty much only how we would work on the visual, completely forgetting everything about game logic (AI, Entities interactions, Quest logic (how do we decide whether or not a quest is completed)).</p> <p>So far, I have found those points:</p> <ul> <li>Physics (collision detection, actual forces, etc.)</li> <li>AI (pathfinding, objectives, etc.)</li> <li>Model management</li> <li>Animation management</li> <li>Scene management</li> <li>Combat management</li> <li>Inventory management</li> <li>Camera (make sure not to render everything that is in the scene)</li> <li>Heightmaps</li> <li>Entities communication (Player with NPC, enemy, other players, etc)</li> <li>Game state</li> <li>Game state save system</li> </ul> <p>In order to reduce the scope of this queston, I'd like it if you could specifically discuss aspects related to developping an RPG type of game. I will also point out that I am using XNA to develop this game, but I have almost no grasp of all the classes available yet (pretty much only using the Game component with some classes that are related to it such as GameTime, SpriteBatch, GraphicDeviceManager) but not much more.</p>
1,116,211
7
0
null
2009-07-12 14:25:07.343 UTC
9
2015-04-26 04:07:06.05 UTC
2010-09-29 18:20:07.843 UTC
null
2,535
null
108,301
null
1
9
components
3,899
<p>I don't know if this is any help, but I have been reading articles from <a href="http://www.gamasutra.com/" rel="nofollow noreferrer">http://www.gamasutra.com/</a> for many years. </p> <p>I don't have a perfect set of tools from the beginning, but your list covers most of the usual trouble for RUNNING the game. But have you found out what each one of the items stands for? How much have you made already? "Inventory Management" sounds very heavy, but some games just need a simple "array" of objects. Takes an hour to program + some graphical integration (if you have your GUI Management done already).</p> <p><strong>How to start planning</strong></p> <p>When I develop games in my spare time, I usually get an idea because another game lacks this function/option. Then I start up what ever development tool I am currently using and try to see if I can make a prototype showing this idea. It's not always about fancy graphics, but most often it's more about finding out how to solve a certain problem. Green and red boxes will help you most of the way, but otherwise, use Google Images and do a quick search for prototype graphics. But remember that these images are probably copyrighted, so only use them for internal test purposes and to explain to your graphic artists what type of game/graphic you want to make.</p> <p>Secondly, you'll find that you need to find/build tools to create the "maps/missions/quests" too. Today many develop their own "object script" where they can easily add new content/path to a game.</p> <p>Many of the ideas we (my friends and I) have been testing started with a certain prototype of the interface, to see if its possible to generate that sort of screen output first. Then we build a quick'n'dirty map/level-editor that can supply us with test maps.</p> <p>No game logic at this point, still figuring out if the game-engine in general is running.</p> <p><strong>My first game-algorithm problem</strong></p> <p>Back when I was in my teens I had a Commodore 64 and I was wondering, how do they sort 10 numbers in order for a Highscore? It took me quite a while to find a "scalable" way of doing this, but I learned a lot about programming too.</p> <p><strong>The second problem I found</strong></p> <p>How do I make a tank/cannon fire a bullet in the correct direction when I fly my helicopter around the screen?</p> <p>I sat down and drew quick sketches of the actual problem, looked at the bullet lines, tried some theories of my own and found something that seemed to be working (by dividing and multiplying positions etc.) later on in school I discovered this to be more or less Pythagoras. LOL!</p> <p><strong>Years and many game attempts later</strong></p> <p>I played "Dune" and the later C&amp;C + the new game Warcraft (v1/v2) - I remember it started to annoyed me how the lame AI worked. The path finding algorithms were frustrating for the player, I thought. They moved in direction of target position and then found a wall, but if the way was to complex, the object just stopped. Argh!</p> <p>So I first sat with large amounts of paper, then I tried to draw certain scenarios where an "object" (tank/ork/soldier) would go from A to B and then suddenly there was a "structure" (building/other object) in the pathway - what then?</p> <p>I learned about <a href="http://en.wikipedia.org/wiki/A*_search_algorithm" rel="nofollow noreferrer">A-star pathfinding</a> (after solving it first on my own in a similar way, then later reading about the reason for this working). A very "cpu heavy" way of finding a path, but I learned a lot from the process of "cracking this nut". These thoughts have helped me a lot developing other game algortimes over time.</p> <p>So what I am saying is: I think you'll have to think more of:</p> <ul> <li>How is the game to be played?</li> <li>What does the user experience look like?</li> <li>Why would the user want to come back to the game?</li> <li>What requirements are needed? Broadband? 19" monitor with 1280x1024?</li> <li>An RPG, yes - but will it be multi-user or single? </li> <li>Do we need a fast network/server setup or do we need to develop a strong AI for the NPCs?</li> </ul> <p>And much more...</p> <p>I am not sure this is what you asked for, but I hope you can use it somehow?</p>
767,912
Riddle: The Square Puzzle
<p>Last couple of days, I have refrained myself from master's studies and have been focusing on this (seemingly simple) puzzle: </p> <hr> <p>There is this 10*10 grid which constitutes a square of 100 available places to go. The aim is to start from a corner and traverse through all the places with respect to some simple "traverse rules" and reach number 100 (or 99 if you're a programmer and start with 0 instead :) </p> <p>The rules for traversing are:<br> 1. Two spaces hop along the vertical and horizontal axis<br> 2. One space hop along the diagonals<br> 3. You can visit each square only once</p> <p>To visualise better, here is a valid example traverse (up to the 8th step):<br> <a href="http://img525.imageshack.us/img525/280/squarepuzzle.png" rel="nofollow noreferrer">Example Traverse http://img525.imageshack.us/img525/280/squarepuzzle.png</a></p> <hr> <p>Manually, I have been working on this puzzle out of boredom. For years, I have tried to solve it by hand from time to time, but I have never gone beyond 96. Sounds easy? Try yourself and see for yourself :)</p> <p>Thus, in order to solve the problem, I have developed a short (around 100 lines of code) program in Python. I am a beginner in this language I wanted to see what I can do.<br> The program simply applies exhaustive try &amp; error solving technique. In other words: brute force depth first search.</p> <p>My question arises from here on: The program, unfortunately cannot solve the problem because the state space is so big that search never ends withouh ever finding a solution. It can go up to number 98 (and prints that) without much difficulty, nonetheless not a complete solution.<br> The program also prints out the length of the search tree it has covered so far. In a couple of minutes, the traverse list from, say, 65th element is covered till the end, for just one single path. This number decreases in exponentially increasing time periods. I have run the code for quite some time and could not get beyond 50 barrier and now I am convinced.</p> <p>It seems that this simple approach will not be enough unless I run it for ever. So, how can I improve my code to be faster and more efficient so that it comes up with solutions?</p> <p>Basically, I am looking forward to see ideas on how to:</p> <ol> <li>Capture and exploit <strong>domain knowledge</strong> specific to this problem</li> <li><p>Apply <strong>programming techniques/tricks</strong> to overcome exhaustion</p> <p>..and finally realize into a substantial solution.</p></li> </ol> <p>Thanks in advance.</p> <hr> <p><strong>Revision</strong><br> Thanks to Dave Webb for relating the problem to domain it belongs: </p> <blockquote> <p>This is very similar to the Knight's Tour problem which relates moving a knight around a chess board without revisiting the same square. Basically it's the same problem but with different "Traverse Rules".</p> </blockquote> <hr>
772,644
7
6
null
2009-04-20 11:41:59.11 UTC
13
2022-01-02 20:00:05.533 UTC
2022-01-02 20:00:05.533 UTC
null
772,868
null
82,049
null
1
21
python|knights-tour
5,480
<p>Eventually, I have come up with the modified Python code to overcome the problem. I've tun the code for a couple of hours and it has already found half a million solutions in a couple of hours.<br> The full set of solutions still require a total exhaustive search, i.e. to let the program run until it finishes with all combinations. However, reaching "a" legitimate solution can be reduced to "linear time".</p> <p>First, things I have learned: </p> <ol> <li><p>Thanks to <a href="https://stackoverflow.com/questions/767912/riddle-the-square-puzzle/767984#767984">Dave Webb's answer</a> and <a href="https://stackoverflow.com/questions/767912/riddle-the-square-puzzle/767991#767991">ammoQ's answer</a>. The problem is indeed an extension of Hamiltonian Path problem as it is NP-Hard. There is no "easy" solution to begin with. There is a famous riddle of <a href="http://en.wikipedia.org/wiki/Knight%27s_tour" rel="nofollow noreferrer">Knight's Tour</a> which is simply the same problem with a different size of board/grid and different traverse-rules. There are many things said and done to elaborate the problem and methodologies and algorithms have been devised.</p></li> <li><p>Thanks to <a href="https://stackoverflow.com/questions/767912/riddle-the-square-puzzle/769302#769302">Joe's answer</a>. The problem can be approached in a bottom-up sense and can be sliced down to solvable sub-problems. Solved sub-problems can be connected in an entry-exit point notion (one's exit point can be connected to one other's entry point) so that the main problem could be solved as a constitution of smaller scale problems. This approach is sound and practical but not complete, though. It can not guarantee to find an answer if it exists.</p></li> </ol> <p>Upon exhaustive brute-force search, here are key points I have developed on the code:</p> <ul> <li><p><a href="http://en.wikipedia.org/wiki/Knight%27s_tour#Warnsdorff.27s_algorithm" rel="nofollow noreferrer">Warnsdorff's algorithm</a>: This algorithm is the key point to reach to a handy number of solutions in a quick way. It simply states that, you should pick your next move to the "least accessible" place and populate your "to go" list with ascending order or accesibility. Least accessible place means the place with least number of possible following moves.</p> <p>Below is the pseudocode (from Wikipedia):</p></li> </ul> <hr> <p>Some definitions:</p> <ul> <li>A position Q is accessible from a position P if P can move to Q by a single knight's move, and Q has not yet been visited.</li> <li>The accessibility of a position P is the number of positions accessible from P.</li> </ul> <p>Algorithm:</p> <blockquote> <p>set P to be a random initial position on the board mark the board at P with the move number "1" for each move number from 2 to the number of squares on the board, let S be the set of positions accessible from the input position set P to be the position in S with minimum accessibility mark the board at P with the current move number return the marked board -- each square will be marked with the move number on which it is visited.</p> </blockquote> <hr> <ul> <li><a href="https://stackoverflow.com/questions/767912/riddle-the-square-puzzle/768497#768497">Checking for islands</a>: A nice exploit of domain knowledge here proved to be handy. If a move (unless it is the last one) would cause <em>any</em> of its neighbors to become an island, i.e. not accessible by any other, then that branch is no longer investigated. Saves considerable amount of time (very roughly 25%) combined with Warnsdorff's algorithm.</li> </ul> <p>And here is my code in Python which solves the riddle (to an acceptable degree considering that the problem is NP-Hard). The code is easy to understand as I consider myself at beginner level in Python. The comments are straightforward in explaining the implementation. Solutions can be displayed on a simple grid by a basic GUI (guidelines in the code).</p> <pre><code># Solve square puzzle import operator class Node: # Here is how the squares are defined def __init__(self, ID, base): self.posx = ID % base self.posy = ID / base self.base = base def isValidNode(self, posx, posy): return (0&lt;=posx&lt;self.base and 0&lt;=posy&lt;self.base) def getNeighbors(self): neighbors = [] if self.isValidNode(self.posx + 3, self.posy): neighbors.append(self.posx + 3 + self.posy*self.base) if self.isValidNode(self.posx + 2, self.posy + 2): neighbors.append(self.posx + 2 + (self.posy+2)*self.base) if self.isValidNode(self.posx, self.posy + 3): neighbors.append(self.posx + (self.posy+3)*self.base) if self.isValidNode(self.posx - 2, self.posy + 2): neighbors.append(self.posx - 2 + (self.posy+2)*self.base) if self.isValidNode(self.posx - 3, self.posy): neighbors.append(self.posx - 3 + self.posy*self.base) if self.isValidNode(self.posx - 2, self.posy - 2): neighbors.append(self.posx - 2 + (self.posy-2)*self.base) if self.isValidNode(self.posx, self.posy - 3): neighbors.append(self.posx + (self.posy-3)*self.base) if self.isValidNode(self.posx + 2, self.posy - 2): neighbors.append(self.posx + 2 + (self.posy-2)*self.base) return neighbors # the nodes go like this: # 0 =&gt; bottom left # (base-1) =&gt; bottom right # base*(base-1) =&gt; top left # base**2 -1 =&gt; top right def solve(start_nodeID, base): all_nodes = [] #Traverse list is the list to keep track of which moves are made (the id numbers of nodes in a list) traverse_list = [start_nodeID] for i in range(0, base**2): all_nodes.append(Node(i, base)) togo = dict() #Togo is a dictionary with (nodeID:[list of neighbors]) tuples togo[start_nodeID] = all_nodes[start_nodeID].getNeighbors() solution_count = 0 while(True): # The search is exhausted if not traverse_list: print "Somehow, the search tree is exhausted and you have reached the divine salvation." print "Number of solutions:" + str(solution_count) break # Get the next node to hop try: current_node_ID = togo[traverse_list[-1]].pop(0) except IndexError: del togo[traverse_list.pop()] continue # end condition check traverse_list.append(current_node_ID) if(len(traverse_list) == base**2): #OMG, a solution is found #print traverse_list solution_count += 1 #Print solution count at a steady rate if(solution_count%100 == 0): print solution_count # The solution list can be returned (to visualize the solution in a simple GUI) #return traverse_list # get valid neighbors valid_neighbor_IDs = [] candidate_neighbor_IDs = all_nodes[current_node_ID].getNeighbors() valid_neighbor_IDs = filter(lambda id: not id in traverse_list, candidate_neighbor_IDs) # if no valid neighbors, take a step back if not valid_neighbor_IDs: traverse_list.pop() continue # if there exists a neighbor which is accessible only through the current node (island) # and it is not the last one to go, the situation is not promising; so just eliminate that stuck_check = True if len(traverse_list) != base**2-1 and any(not filter(lambda id: not id in traverse_list, all_nodes[n].getNeighbors()) for n in valid_neighbor_IDs): stuck_check = False # if stuck if not stuck_check: traverse_list.pop() continue # sort the neighbors according to accessibility (the least accessible first) neighbors_ncount = [] for neighbor in valid_neighbor_IDs: candidate_nn = all_nodes[neighbor].getNeighbors() valid_nn = [id for id in candidate_nn if not id in traverse_list] neighbors_ncount.append(len(valid_nn)) n_dic = dict(zip(valid_neighbor_IDs, neighbors_ncount)) sorted_ndic = sorted(n_dic.items(), key=operator.itemgetter(1)) sorted_valid_neighbor_IDs = [] for (node, ncount) in sorted_ndic: sorted_valid_neighbor_IDs.append(node) # if current node does have valid neighbors, add them to the front of togo list # in a sorted way togo[current_node_ID] = sorted_valid_neighbor_IDs # To display a solution simply def drawGUI(size, solution): # GUI Code (If you can call it a GUI, though) import Tkinter root = Tkinter.Tk() canvas = Tkinter.Canvas(root, width=size*20, height=size*20) #canvas.create_rectangle(0, 0, size*20, size*20) canvas.pack() for x in range(0, size*20, 20): canvas.create_line(x, 0, x, size*20) canvas.create_line(0, x, size*20, x) cnt = 1 for el in solution: canvas.create_text((el % size)*20 + 4,(el / size)*20 + 4,text=str(cnt), anchor=Tkinter.NW) cnt += 1 root.mainloop() print('Start of run') # it is the moment solve(0, 10) #Optional, to draw a returned solution #drawGUI(10, solve(0, 10)) raw_input('End of Run...') </code></pre> <p>Thanks to all everybody sharing their knowledge and ideas.</p>
1,027,395
Detecting Outlook autoreply/out-of-office emails
<p>Been googling for this and haven't found anything ...</p> <p>Does anybody know if there is a way, given an Outlook email item, to detect whether it was sent by the "Out Of Office Assistant"? Is there any property that Outlook sets on the object, or any header information, that identifies an email as such? I was hoping not to have to parse the subject line for "Out Of Office", etc.</p> <p>It would be great if there were some standard, so autoreplies from other email services (like Gmail) could also be detected, but for me Outlook is the highest priority.</p>
1,027,576
7
1
null
2009-06-22 14:04:42.933 UTC
12
2021-12-20 15:57:41.58 UTC
2020-06-24 07:47:53.557 UTC
null
100,297
null
65,712
null
1
32
vba|outlook|email-headers
36,739
<p>There is a header field (<a href="http://www.iana.org/assignments/auto-submitted-keywords/auto-submitted-keywords.xhtml" rel="noreferrer">http://www.iana.org/assignments/auto-submitted-keywords/auto-submitted-keywords.xhtml</a>) but it seems that MS Outlook does not set it (at least, not Outlook 2003). I guess that you have to parse the subject line.</p>
226,420
C#: How to create an attribute on a method triggering an event when it is invoked?
<p>Is there a way in C# or .NET in general to create an attribute on a method which triggers an event when the method is invoked? Ideally, I would be able to run custom actions before and after the invocation of the method.</p> <p>I mean something like this:</p> <pre><code>[TriggersMyCustomAction()] public void DoSomeStuff() { } </code></pre> <p>I am totally clueless how to do it or if it possible at all, but <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx" rel="noreferrer">System.Diagnostic.ConditionalAttribute</a> might do a similar thing in the background. I am not sure though.</p> <p><strong>EDIT</strong>: I forgot to mention that due to the circumstances of my specific case, performance is not really an issue.</p>
226,440
7
2
null
2008-10-22 15:54:57.003 UTC
16
2020-04-08 06:42:00.707 UTC
2018-06-26 11:57:08.157 UTC
DrJokepu
1,016,343
DrJokepu
8,954
null
1
41
c#|.net|events|methods|attributes
46,263
<p>The only way I know how to do this is with <a href="https://www.postsharp.net/" rel="noreferrer">PostSharp</a>. It post-processes your IL and can do things like what you asked for.</p>
1,302,243
Selecting a float in MySQL
<p>I am trying to do a <code>SELECT</code> match on a table based upon an identifier and a price, such as:</p> <pre><code>SELECT * FROM `table` WHERE `ident`='ident23' AND `price`='101.31'; </code></pre> <p>The above returns zero rows, while if you remove the <code>price='101.31'</code> bit it returns the correct row. </p> <p>Doing a...</p> <pre><code>SELECT * FROM `table`; </code></pre> <p>Returns the same row as above and quite clearly states that <code>price='101.31'</code>. Yet select fails to match it. Changing <code>=</code> to <code>&lt;=</code> makes it work - but this is not exactly a solution.</p> <p>Is there a way of casting the MySQL float to 2 digits before the operation is performed on it, thus making the above <code>SELECT</code> work (or some other solution)?</p> <p>Thanks!</p>
1,302,270
8
0
null
2009-08-19 19:48:51.667 UTC
5
2018-09-27 09:31:44.23 UTC
2009-08-19 19:52:57.29 UTC
null
53,114
null
130,417
null
1
27
php|mysql|floating-point|database
52,520
<p>Casting to a decimal worked for me:</p> <pre><code>SELECT * FROM table WHERE CAST(price AS DECIMAL) = CAST(101.31 AS DECIMAL); </code></pre> <p>However, you may want to consider just making the <code>price</code> column a DECIMAL in the first place. DECIMAL is generally considered to be the best type to use when dealing with monetary values.</p>
316,166
How do I include a common file in VBScript (similar to C #include)?
<p>VBScript doesn't appear to have a way to include a common file of functions.</p> <p>Is there a way to achieve this?</p>
316,491
8
1
2008-11-25 05:43:24.523 UTC
2008-11-25 02:23:31.603 UTC
16
2017-05-13 20:55:26.05 UTC
2009-07-15 06:12:51.75 UTC
null
113,116
Pax
14,860
null
1
47
vbscript|include
90,757
<p>The "Windows Script Host" framework (if ya want to call it that), offers an XML wrapper document that adds functionality over regular vbs files. One of which is the ability to include external script files of both the VBscript and Jscript flavors. I never got very deep into it, but I think it would do what you're wanting to do. <a href="http://msdn.microsoft.com/en-us/library/15x4407c(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/15x4407c(VS.85).aspx</a></p> <p>You can include JavaScript, VBScript, or modules of other WScript script languages. </p> <p>Example WSF file: </p> <pre><code>&lt;job id="IncludeExample"&gt; &lt;script language="JavaScript" src="sprintf.js"/&gt; &lt;script language="VBScript" src="logging.vbs"/&gt; &lt;script language="VBScript" src="iis-queryScriptMaps.vbs"/&gt; &lt;/job&gt; </code></pre> <p>If the above file is called "iis-scriptmaps.wsf", run it this way with cscript.exe: </p> <pre><code>cscript.exe iis-scriptmaps.wsf </code></pre>