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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8,745,051 | Postgres manually alter sequence | <p>I'm trying to set a sequence to a specific value.</p>
<pre><code>SELECT setval('payments_id_seq'), 21, true;
</code></pre>
<p>This gives an error:</p>
<blockquote>
<p><code>ERROR: function setval(unknown) does not exist</code></p>
</blockquote>
<p>Using <code>ALTER SEQUENCE</code> doesn't seem to work either?</p>
<pre><code>ALTER SEQUENCE payments_id_seq LASTVALUE 22;
</code></pre>
<p>How can this be done?</p>
<p>Ref: <a href="https://www.postgresql.org/docs/current/functions-sequence.html" rel="nofollow noreferrer">https://www.postgresql.org/docs/current/functions-sequence.html</a></p> | 8,745,101 | 6 | 1 | null | 2012-01-05 15:28:58.447 UTC | 57 | 2022-08-20 01:42:23.507 UTC | 2022-08-20 01:42:23.507 UTC | null | 939,860 | null | 149,664 | null | 1 | 294 | sql|postgresql|ddl|database-sequence | 314,816 | <p>The parentheses are misplaced:</p>
<pre><code>SELECT setval('payments_id_seq', 21, true); -- next value will be 22
</code></pre>
<p>Otherwise you're calling <code>setval</code> with a single argument, while it requires two or three.</p>
<p>This is the same as <code>SELECT setval('payments_id_seq', 21)</code></p> |
27,053,436 | Segue in SKScene to UIViewController | <p>In my GameScene.swift file, I am trying to perform a segue back to my Menu View Controller like so:</p>
<pre><code>func returnToMainMenu(){
var vc: UIViewController = UIViewController()
vc = self.view!.window!.rootViewController!
vc.performSegueWithIdentifier("menu", sender: vc)
}
</code></pre>
<p>This method is run when a node is tapped:</p>
<pre><code>override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if gameOn == false{
if restartBack.containsPoint(location){
self.restartGame()
}
else if menuBack.containsPoint(location){
self.returnToMainMenu()
}
else if justBegin == true{
self.restartGame()
}
}
}
}
</code></pre>
<p>Where <code>menuBack</code> is the button back to the menu. Every time I run this code, I am thrown an NSException:</p>
<pre><code>Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Receiver (<ProxyBlock.Menu: 0x165a3e90>) has no segue with identifier 'menu''
</code></pre>
<p>I checked my segue's identifier and it was indeed "menu".</p> | 27,056,327 | 2 | 2 | null | 2014-11-21 03:02:30.983 UTC | 8 | 2020-03-11 03:57:18.947 UTC | 2015-02-17 10:00:20 UTC | null | 201,863 | null | 3,896,750 | null | 1 | 7 | ios|swift|sprite-kit|segue | 5,514 | <p>You are calling the segue on the root viewController. I think that is the problem. You need to call the segue on the scene's viewController instead (where I am assuming you have created the segue, hence it is not being found on the root viewController). </p>
<p>Now the problem is that an SKScene does not have direct access to it's viewController, but just the view in which it is contained. You need to create a pointer to it manually. This can be done by creating a property for the SKScene:</p>
<pre><code>class GameScene: SKScene {
weak var viewController: UIViewController?
...
}
</code></pre>
<p>Then, in the viewController class, just before <code>skView.presentScene(scene)</code></p>
<pre><code>scene.viewController = self
</code></pre>
<p>Now, you can access the viewController directly. Simply call the segue on this viewController:</p>
<pre><code>func returnToMainMenu(){
viewController?.performSegueWithIdentifier("menu", sender: vc)
}
</code></pre> |
27,354,734 | dplyr mutate rowSums calculations or custom functions | <p>I'm trying to mutate a new variable from sort of row calculation,
say <code>rowSums</code> as below</p>
<pre><code>iris %>%
mutate_(sumVar =
iris %>%
select(Sepal.Length:Petal.Width) %>%
rowSums)
</code></pre>
<p>the result is that "sumVar" is truncated to its first value(10.2): </p>
<pre><code>Source: local data frame [150 x 6]
Groups: <by row>
Sepal.Length Sepal.Width Petal.Length Petal.Width Species sumVar
1 5.1 3.5 1.4 0.2 setosa 10.2
2 4.9 3.0 1.4 0.2 setosa 10.2
3 4.7 3.2 1.3 0.2 setosa 10.2
4 4.6 3.1 1.5 0.2 setosa 10.2
5 5.0 3.6 1.4 0.2 setosa 10.2
6 5.4 3.9 1.7 0.4 setosa 10.2
..
Warning message:
Truncating vector to length 1
</code></pre>
<p>Should it be <code>rowwise</code> applied? Or what's the right verb to use in these kind of calculations.</p>
<p><strong>Edit:</strong></p>
<p>More specifically, is there any way to realize the inline custom function with <code>dplyr</code>?</p>
<p>I'm wondering if it is possible do something like:</p>
<pre><code>iris %>%
mutate(sumVar = colsum_function(Sepal.Length:Petal.Width))
</code></pre> | 63,504,611 | 6 | 3 | null | 2014-12-08 09:15:09.237 UTC | 26 | 2020-08-20 12:20:52.613 UTC | 2014-12-10 06:25:01.67 UTC | null | 3,744,499 | null | 3,744,499 | null | 1 | 75 | r|dplyr | 79,769 | <p>You can use <a href="https://dplyr.tidyverse.org/articles/rowwise.html" rel="noreferrer"><code>rowwise()</code></a> function:</p>
<pre><code>iris %>%
rowwise() %>%
mutate(sumVar = sum(c_across(Sepal.Length:Petal.Width)))
#> # A tibble: 150 x 6
#> # Rowwise:
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species sumVar
#> <dbl> <dbl> <dbl> <dbl> <fct> <dbl>
#> 1 5.1 3.5 1.4 0.2 setosa 10.2
#> 2 4.9 3 1.4 0.2 setosa 9.5
#> 3 4.7 3.2 1.3 0.2 setosa 9.4
#> 4 4.6 3.1 1.5 0.2 setosa 9.4
#> 5 5 3.6 1.4 0.2 setosa 10.2
#> 6 5.4 3.9 1.7 0.4 setosa 11.4
#> 7 4.6 3.4 1.4 0.3 setosa 9.7
#> 8 5 3.4 1.5 0.2 setosa 10.1
#> 9 4.4 2.9 1.4 0.2 setosa 8.9
#> 10 4.9 3.1 1.5 0.1 setosa 9.6
#> # ... with 140 more rows
</code></pre>
<p>"<code>c_across()</code> uses tidy selection syntax so you can to succinctly select many variables"'</p>
<p>Finally, if you want, you can use <code>%>% ungroup</code> at the end to exit from rowwise.</p> |
27,016,868 | What is the difference between a physical address and MAC address in networking? | <p>Somewhere I have read that both physical address and MAC address are the same,which is exactly the same attached with the NIC of a machine. And also in some other place I have read that a router is forwarding data packets based on the information such as Physical and Logical addresses available from a data packet. I have the knowledge that a MAC address will never go beyond the LAN's gateway. Then how come the other routers collect the information regarding my MAC address from a data packet send by me?</p>
<p>Am I supposed to believe that physical address is different from MAC address when comes into networking?</p> | 27,017,351 | 3 | 3 | null | 2014-11-19 12:29:03.233 UTC | 3 | 2018-05-28 12:30:04.96 UTC | 2014-11-24 20:51:37.95 UTC | null | 64,046 | null | 4,202,092 | null | 1 | 9 | networking|ip|mac-address | 40,660 | <p>Physical address and MAC address are indeed the same.
They are used to communicate between devices on Ethernet networks.
When you send a request to a remote host's IP address (access a website for instance) your computer sends that request to your LAN's gateway (your router) and it uses its physical (MAC) address as the destination of the message but the logical (IP) address of the host for its final destination.
The router then forwards that message onward and knows who to return the reply to.</p> |
688,531 | Deleting Global Temporary Tables (##tempTable) in SQL Server | <p>Does SQL server automatically purge these out after a given length of inactivity or do I need to worry about purging them automatically? If so, how do I query for a list of tables to purge?</p> | 688,540 | 4 | 0 | null | 2009-03-27 04:14:18.75 UTC | null | 2022-01-17 23:52:06.913 UTC | 2009-03-27 23:22:46.383 UTC | Jeff Atwood | 1 | Jeff | 13,338 | null | 1 | 21 | sql-server|temp-tables | 49,049 | <p>Local temporary tables are destroyed when you close your connection to SQL Server. There is no need to manually purge them under normal circumstances. If you maintain a persistent connection, or connection pooling, you may want to get in the habit of dropping temporary tables immediately after use.</p>
<p>Global temporary tables, on the other hand, since they are visible to all users in a given database, are destroyed along with the last connection which references them.</p> |
1,100,409 | How can I apply a background image to a text input without losing the default border in Firefox and WebKit browsers? | <p>For some reason most modern browsers will stop applying their default input border style to text boxes if you give them a background image. Instead you get that ugly inset style. From what I can tell there's no CSS way to apply the default browser style either.</p>
<p>IE 8 doesn't have this problem. Chrome 2 and Firefox 3.5 do and I assume other browsers as well. From what I've read online IE 7 has the same problem, but that post didn't have a solution.</p>
<p>Here's an example:</p>
<pre><code><html>
<head>
<style>
.pictureInput {
background-image: url(http://storage.conduit.com/images/searchengines/search_icon.gif);
background-position: 0 1px;
background-repeat: no-repeat;
}
</style>
<body>
<input type="text" class="pictureInput" />
<br />
<br />
<input type="text">
</body>
</html>
</code></pre>
<p>In Chrome 2 it looks like this: <a href="http://www.screencast.com/users/jadeonly/folders/Snagit/media/d4ee9819-c92a-4bc2-b84e-e3a4ed6843b6" rel="nofollow noreferrer">http://www.screencast.com/users/jadeonly/folders/Snagit/media/d4ee9819-c92a-4bc2-b84e-e3a4ed6843b6</a></p>
<p>And in Firefox 3.5: <a href="http://www.screencast.com/users/jadeonly/folders/Snagit/media/d70dd690-9273-45fb-9893-14b38202ddcc" rel="nofollow noreferrer">http://www.screencast.com/users/jadeonly/folders/Snagit/media/d70dd690-9273-45fb-9893-14b38202ddcc</a></p>
<p><strong>Update: JS Solution:</strong> I'm still hoping to find a pure CSS-on-the-input solution, but here's the workaround I'll use for now. Please note this is pasted right out of my app so isn't a nice, stand alone example like above. I've just included the relevant parts out of my large web app. You should be able to get the idea. The HTML is the input with the "link" class. The large vertical background position is because it's a sprite. Tested in IE6, IE7, IE8, FF2, FF3.5, Opera 9.6, Opera 10, Chrome 2, Safari 4. I need to tweak the background position a couple pixels in some browsers still:</p>
<p>JS:</p>
<pre><code> $$('input.link').each(function(el) {
new Element('span',{'class':'linkIcon'}).setText(' ').injectBefore(el);
if (window.gecko) el.setStyle('padding', '2px 2px 2px 19px');
});
</code></pre>
<p>CSS:</p>
<pre><code>input.link { padding-left: 19px; }
span.linkIcon { z-index: 2; width: 19px; height: 19px; position: absolute; background-image: url(img/fields.gif); background-position: 1px -179px; background-repeat: no-repeat; }
</code></pre>
<p><strong>Update: CSS Close Enough Solution:</strong> Based on the suggestion from kRON here's the CSS to make the inputs match FF and IE in Vista which makes a good choice if you decide to give up on pure defaults and enforce one style. I have modified his slightly and added the "blueish" effects:</p>
<p>CSS:</p>
<pre><code>input[type=text], select, textarea {
border-top: 1px #acaeb4 solid;
border-left: 1px #dde1e7 solid;
border-right: 1px #dde1e7 solid;
border-bottom: 1px #e3e9ef solid;
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
padding: 2px;
}
input[type=text]:hover, select:hover, textarea:hover, input[type=text]:focus, select:focus, textarea:focus {
border-top: 1px #5794bf solid;
border-left: 1px #c5daed solid;
border-right: 1px #b7d5ea solid;
border-bottom: 1px #c7e2f1 solid;
}
select { border: 1px; }
</code></pre> | 1,112,179 | 4 | 4 | null | 2009-07-08 20:33:18.813 UTC | 5 | 2019-03-27 23:59:39.143 UTC | 2009-09-29 16:45:23.487 UTC | null | 135,241 | null | 135,241 | null | 1 | 31 | css|input|border|background-image | 55,445 | <p>When you change border or background style on text inputs They revert back to the very basic rendering mode. Text inputs that are os-style are usually overlays (like flash is) which are rendered on top of the document.</p>
<p>I do not believe there is a pure CSS fix to your problem. Best thing to do - in my opinion - is to pick a style that you like and emulate it with CSS. So that no matter what browser you're in, the inputs will look the same. You can still have hover effects and the like. OS X style glow effects might be tricky, but I'm sure it is doable.</p>
<p>@Alex Morales: Your solution is redundant. border: 0; is ignored in favor of border: 1px solid #abadb3; and results in unnecessary bytes transferred across the wire.</p> |
91,110 | How to match a single quote in sed | <p>How to match a single quote in sed if the expression is enclosed in single quotes:</p>
<pre><code>sed -e '...'
</code></pre>
<p>For example need to match this text:</p>
<pre><code>'foo'
</code></pre> | 91,176 | 4 | 2 | null | 2008-09-18 09:12:09.57 UTC | 10 | 2020-12-03 19:55:51.857 UTC | 2020-06-09 17:33:27.747 UTC | null | 10,248,678 | grigy | 1,692,070 | null | 1 | 44 | bash|shell|sed|escaping | 43,106 | <p>You can either use:</p>
<pre class="lang-none prettyprint-override"><code>"texta'textb" (APOSTROPHE inside QUOTATION MARKs)
</code></pre>
<p>or</p>
<pre class="lang-none prettyprint-override"><code>'texta'\''textb' (APOSTROPHE text APOSTROPHE, then REVERSE SOLIDUS, APOSTROPHE, then APOSTROPHE more text APOSTROPHE)
</code></pre>
<p>I used unicode character names. REVERSE SOLIDUS is more commonly known as backslash.</p>
<p>In the latter case, you close your apostrophe, then shell-quote your apostrophe with a backslash, then open another apostrophe for the rest of the text.</p> |
764,134 | Ruby's yield feature in relation to computer science | <p>I recently discovered Ruby's blocks and yielding features, and I was wondering: where does this fit in terms of computer science theory? Is it a functional programming technique, or something more specific?</p> | 765,126 | 4 | 0 | null | 2009-04-18 20:27:03.7 UTC | 24 | 2012-11-29 01:44:03.96 UTC | null | null | null | null | 90,155 | null | 1 | 50 | ruby|functional-programming|yield | 10,431 | <p>Ruby's <code>yield</code> is not an iterator like in C# and Python. <code>yield</code> itself is actually a really simple concept once you understand how blocks work in Ruby.</p>
<p>Yes, blocks are a functional programming feature, even though Ruby is not properly a functional language. In fact, Ruby uses the method <code>lambda</code> to create block objects, which is borrowed from Lisp's syntax for creating anonymous functions — which is what blocks are. From a computer science standpoint, Ruby's blocks (and Lisp's lambda functions) are <a href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29" rel="noreferrer">closures</a>. In Ruby, methods usually take only one block. (You can pass more, but it's awkward.)</p>
<p>The <code>yield</code> keyword in Ruby is just a way of calling a block that's been given to a method. These two examples are equivalent:</p>
<pre><code>def with_log
output = yield # We're calling our block here with yield
puts "Returned value is #{output}"
end
def with_log(&stuff_to_do) # the & tells Ruby to convert into
# an object without calling lambda
output = stuff_to_do.call # We're explicitly calling the block here
puts "Returned value is #{output}"
end
</code></pre>
<p>In the first case, we're just assuming there's a block and say to call it. In the other, Ruby wraps the block in an object and passes it as an argument. The first is more efficient and readable, but they're effectively the same. You'd call either one like this:</p>
<pre><code>with_log do
a = 5
other_num = gets.to_i
@my_var = a + other_num
end
</code></pre>
<p>And it would print the value that wound up getting assigned to <code>@my_var</code>. (OK, so that's a completely stupid function, but I think you get the idea.)</p>
<p>Blocks are used for a lot of things in Ruby. Almost every place you'd use a loop in a language like Java, it's replaced in Ruby with methods that take blocks. For example,</p>
<pre><code>[1,2,3].each {|value| print value} # prints "123"
[1,2,3].map {|value| 2**value} # returns [2, 4, 8]
[1,2,3].reject {|value| value % 2 == 0} # returns [1, 3]
</code></pre>
<p>As Andrew noted, it's also commonly used for opening files and many other places. Basically anytime you have a standard function that could use some custom logic (like sorting an array or processing a file), you'll use a block. There are other uses too, but this answer is already so long I'm afraid it will cause heart attacks in readers with weaker constitutions. Hopefully this clears up the confusion on this topic.</p> |
60,726,180 | Angular 9: Value at position X in the NgModule.imports is not a reference | <p>I upgraded an Angular App from v8 to v9. The project imports a custom UI library using Angular 8 and moment.js.</p>
<p>When I build it:
<br></p>
<ol>
<li><strong>It generates a warning:</strong></li>
</ol>
<pre><code>WARNING in Entry point '@myLib/catalogue' contains deep imports into
'/Users/xyz/Projects/forms-frontend/node_modules/moment/locale/de'.
This is probably not a problem, but may cause the compilation of entry points to be out of order.
</code></pre>
<p>In the <code>@myLib/catalogue.js</code> file of the library (inside node_modules folder), the moment.js DE locale is imported as following:</p>
<pre><code>import 'moment/locale/de';
</code></pre>
<p><br></p>
<ol start="2">
<li><strong>Compilation errors are also triggered:</strong></li>
</ol>
<pre><code>ERROR in Failed to compile entry-point @myLib/catalogue (es2015 as esm2015) due to compilation errors:
node_modules/@myLib/catalogue/fesm2015/catalogue.js:213:26 - error NG1010: Value at position 2 in the NgModule.imports of FormInputModule is not a reference: [object Object]
213 imports: [
~
214 CommonModule,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
...
219 TranslateModule
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
220 ],
~~~~~~~~~~~~~~~~~
</code></pre>
<p>The text of the warning seems explaining exactly the compilation error, where the position (2 in this case) is out of range of the imports array.</p>
<p>I have seen different articles/<a href="https://github.com/angular/angular/issues/35615" rel="noreferrer">github issues</a> about deep-links, but no working solution. </p> | 61,246,450 | 7 | 1 | null | 2020-03-17 16:13:57.133 UTC | 2 | 2022-09-11 08:22:45.98 UTC | null | null | null | null | 706,293 | null | 1 | 23 | angular|deeplink|angular-cli-v9 | 61,410 | <p>In my case the issue was related to an imported library, that was not Angular v9 compatible (among other things it was not using deep links to Angular Material and moment.js).</p>
<p>I was lucky as the library is an intern one and I could fix these points and republish it. After that it built without any problems or changes on my project side.</p> |
37,293,314 | Unable to find explicit activity class. Have you declared this activity in your AndroidManifest.xml | <p>I'm trying to implement a PreferenceActivity in my app, following the accepted answer in <a href="https://stackoverflow.com/questions/23523806/how-do-you-create-preference-activity-and-preference-fragment-on-android">this question</a></p>
<p>I get the above exception</p>
<pre><code>android.content.ActivityNotFoundException: Unable to find explicit activity class {com.iphonik.chameleon/com.iphonik.AppPreferenceActivity}; have you declared this activity in your AndroidManifest.xml?
</code></pre>
<p>AndroidManifest.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.iphonik.chameleon">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@android:style/Theme.NoTitleBar">
<activity android:name=".MainMenu">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Movies" />
<activity android:name=".SettingsActivity" />
<activity android:name=".InfoActivity" />
<receiver
android:name=".AppBroadcastReciever"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<activity android:name=".Info2Activity" />
<activity android:name=".ItemDetailActivity" />
<activity android:name=".TVActivity" />
<activity android:name="com.iphonik.chameleon.AppPreferenceActivity"
android:label="Preferences">
</activity>
</application>
</manifest>
</code></pre>
<p>The activity launching code</p>
<pre><code>@Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()) {
case R.id.preferences:
Intent intent = new Intent();
intent.setClassName(this, "com.iphonik.AppPreferenceActivity");
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
</code></pre> | 37,293,733 | 10 | 1 | null | 2016-05-18 07:48:03.5 UTC | 2 | 2021-06-10 05:31:25.477 UTC | 2017-05-23 12:02:35.313 UTC | null | -1 | null | 1,800,515 | null | 1 | 8 | android|android-manifest | 41,321 | <p>declare your activity like this:</p>
<pre><code><activity
android:name=".AppPreferenceActivity"
android:label="Preferences" >
<intent-filter>
<action android:name="com.iphonik.chameleon.AppPreferenceActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</code></pre>
<p>and use it:</p>
<pre><code>Intent i = new Intent("com.iphonik.chameleon.AppPreferenceActivity");
</code></pre> |
1,277,869 | Recent Activities in Ruby on Rails | <p>What is the best way to implement a StackOverflow-style Recent Activities page?</p>
<p>I have a Gallery with user's photos and I want them to be notified when <strong>other</strong> users comment or vote their photos.</p>
<p>Should I create a new table which contains recent activities (updated whenever a user posts a comment or votes) or should I simply use a MySQL query?</p> | 1,278,030 | 2 | 0 | null | 2009-08-14 13:34:57.81 UTC | 10 | 2012-09-11 08:59:51.953 UTC | null | null | null | null | 51,387 | null | 1 | 4 | ruby-on-rails | 2,705 | <p>The short answer is : it depends. If you only need most recent activities and don't need to keep track of activities, or a full 'activity feed' feature, SQL is the way to go. but if you see the need to do a full activity feed kind thing, You can create a model for it. </p>
<p>We did a activity stream recently on our project. Here is how we modeled it</p>
<pre><code>Class Activity
belongs_to :user_activities # all the people that cares about the activity
belongs_to :actor, class_name='user' # the actor that cause the activity
belongs_to :target, :polymorphic => true # the activity target(e.g. if you vote an answer, the target can be the answer )
belongs_to :subtarget, :polymorphic => true # the we added this later since we feel the need for a secondary target, e.g if you rate an answer, target is your answer, secondary target is your rating.
def self.add(actor, activity_type, target, subtarget = nil)
activity = Activity.new(:actor => actor, :activity_type => activity_type, :target => target, :subtarget => subtarget)
activity.save!
activity
end
end
</code></pre>
<p>in the answer_controller we do </p>
<pre><code>Class AnswersController
def create
...
Activity.add(current_user, ActivityType::QUESTION_ANSWERED, @answer)
...
end
end
</code></pre>
<p>To get a recent activity list from a user we do </p>
<pre><code>@activities = @user.activities
</code></pre> |
18,754,141 | Unordered List with checkmarks list-style-positions-outside Text aligned on the left vertically | <p>I am trying to have an unordered list with check-marks and have my text line up in the left and not have my second line of text float to the left and go under the check-marks.</p>
<p>Does anyone know how to make this work?</p> | 18,754,435 | 1 | 2 | null | 2013-09-12 02:00:55.433 UTC | 10 | 2015-10-25 19:26:18.607 UTC | 2015-10-25 19:26:18.607 UTC | null | 444,991 | null | 1,195,424 | null | 1 | 17 | html|css|html-lists | 44,920 | <p>The below code helps you in understanding. <a href="http://jsfiddle.net/AeY2x/1/">Here's a JSFiddle demo</a>.</p>
<pre><code>li:before
{
content: '✔';
margin-left: -1em;
margin-right: .100em;
}
ul
{
padding-left: 20px;
text-indent: 2px;
list-style: none;
list-style-position: outside;
}
</code></pre>
<p>Refer this link to get the tick mark: <a href="http://amp-what.com/#q=check%20mark">http://amp-what.com/#q=check%20mark</a></p>
<p>Paste the code in the content property of <code>li</code> to get the check mark.
I hope this will help you. Please vote.</p> |
31,313,863 | How to delete my follower at github? | <p>Is it possible to do?</p>
<p>If yes, could you please provide a <a href="http://curl.haxx.se" rel="noreferrer">curl</a> example?</p> | 33,641,426 | 3 | 1 | null | 2015-07-09 09:44:01.953 UTC | 2 | 2018-02-27 11:36:58.443 UTC | null | null | null | null | 4,990,584 | null | 1 | 36 | github|github-api | 15,749 | <p>Removing a follower on Github in fact <em>is</em> possible with this workaround:</p>
<p>Block the user who watches you, as described <a href="https://help.github.com/articles/blocking-a-user-from-your-personal-account/" rel="noreferrer">in the github help</a>.</p>
<p>Then unblock him again. </p>
<p>After that he will not be blocked anymore and he will also no longer follow you.</p> |
25,784,410 | What is TEXTIMAGE_ON [PRIMARY]? | <p>I worked on many tables and all had this thing:</p>
<pre><code>CREATE TABLE Persons(
[id] [int] IDENTITY(1,1) NOT NULL,
[modified_on] [datetime] NULL,
[modified_by] [varchar](200) NULL,
)
ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
</code></pre>
<p>What is <code>TEXTIMAGE_ON [PRIMARY]</code> in SQL Server/Transact-SQL?</p> | 25,784,480 | 3 | 1 | null | 2014-09-11 09:56:27.243 UTC | 13 | 2017-12-28 08:41:37.497 UTC | 2015-06-30 06:52:08.807 UTC | null | 1,399,310 | null | 3,936,505 | null | 1 | 151 | sql-server | 121,993 | <p>From the <a href="http://msdn.microsoft.com/en-GB/library/ms174979.aspx">MSDN</a></p>
<blockquote>
<p><strong>TEXTIMAGE_ON { filegroup | "default" }</strong></p>
<p>Indicates that the text, ntext, image, xml, varchar(max),
nvarchar(max), varbinary(max), and CLR user-defined type columns
(including geometry and geography) are stored on the specified
filegroup.</p>
<p>TEXTIMAGE_ON is not allowed if there are no large value columns in the
table. TEXTIMAGE_ON cannot be specified if <code><partition_scheme></code> is
specified. If "default" is specified, or if TEXTIMAGE_ON is not
specified at all, the large value columns are stored in the default
filegroup. The storage of any large value column data specified in
CREATE TABLE cannot be subsequently altered.</p>
<p>NOTE: In this context, default is not a keyword. It is an identifier for the default filegroup and must be delimited, as in TEXTIMAGE_ON "default" or TEXTIMAGE_ON [default]. If "default" is specified, the QUOTED_IDENTIFIER option must be ON for the current session. This is the default setting.</p>
</blockquote> |
25,586,901 | How to find document and single subdocument matching given criterias in MongoDB collection | <p>I have collection of products. Each product contains array of items.</p>
<pre><code>> db.products.find().pretty()
{
"_id" : ObjectId("54023e8bcef998273f36041d"),
"shop" : "shop1",
"name" : "product1",
"items" : [
{
"date" : "01.02.2100",
"purchasePrice" : 1,
"sellingPrice" : 10,
"count" : 15
},
{
"date" : "31.08.2014",
"purchasePrice" : 10,
"sellingPrice" : 1,
"count" : 5
}
]
}
</code></pre>
<p>So, can you please give me an advice, how I can query MongoDB to retrieve all products with only single item which date is equals to the date I pass to query as parameter.</p>
<p>The result for "31.08.2014" must be: </p>
<pre><code> {
"_id" : ObjectId("54023e8bcef998273f36041d"),
"shop" : "shop1",
"name" : "product1",
"items" : [
{
"date" : "31.08.2014",
"purchasePrice" : 10,
"sellingPrice" : 1,
"count" : 5
}
]
}
</code></pre> | 25,587,818 | 3 | 1 | null | 2014-08-30 21:27:38.68 UTC | 11 | 2021-05-08 10:03:01.363 UTC | 2017-06-27 11:16:36.517 UTC | null | 2,313,887 | null | 485,107 | null | 1 | 19 | mongodb|mongodb-query|aggregation-framework | 31,677 | <p>What you are looking for is <a href="http://docs.mongodb.org/manual/reference/operator/projection/positional/" rel="noreferrer">the positional <code>$</code></a> operator and "projection". For a single field you need to match the required array element using "dot notation", for more than one field use <a href="http://docs.mongodb.org/manual/reference/operator/query/elemMatch/" rel="noreferrer"><strong><code>$elemMatch</code></strong></a>:</p>
<pre class="lang-js prettyprint-override"><code>db.products.find(
{ "items.date": "31.08.2014" },
{ "shop": 1, "name":1, "items.$": 1 }
)
</code></pre>
<p>Or the <code>$elemMatch</code> for more than one matching field:</p>
<pre class="lang-js prettyprint-override"><code>db.products.find(
{ "items": {
"$elemMatch": { "date": "31.08.2014", "purchasePrice": 1 }
}},
{ "shop": 1, "name":1, "items.$": 1 }
)
</code></pre>
<p>These work for a single array element only though and only one will be returned. If you want more than one array element to be returned from your conditions then you need more advanced handling with the aggregation framework.</p>
<pre class="lang-js prettyprint-override"><code>db.products.aggregate([
{ "$match": { "items.date": "31.08.2014" } },
{ "$unwind": "$items" },
{ "$match": { "items.date": "31.08.2014" } },
{ "$group": {
"_id": "$_id",
"shop": { "$first": "$shop" },
"name": { "$first": "$name" },
"items": { "$push": "$items" }
}}
])
</code></pre>
<p>Or possibly in shorter/faster form since MongoDB 2.6 where your array of items contains unique entries:</p>
<pre class="lang-js prettyprint-override"><code>db.products.aggregate([
{ "$match": { "items.date": "31.08.2014" } },
{ "$project": {
"shop": 1,
"name": 1,
"items": {
"$setDifference": [
{ "$map": {
"input": "$items",
"as": "el",
"in": {
"$cond": [
{ "$eq": [ "$$el.date", "31.08.2014" ] },
"$$el",
false
]
}
}},
[false]
]
}
}}
])
</code></pre>
<p>Or possibly with <a href="http://docs.mongodb.org/manual/reference/operator/aggregation/redact/" rel="noreferrer"><strong><code>$redact</code></strong></a>, but a little contrived:</p>
<pre class="lang-js prettyprint-override"><code>db.products.aggregate([
{ "$match": { "items.date": "31.08.2014" } },
{ "$redact": {
"$cond": [
{ "$eq": [ { "$ifNull": [ "$date", "31.08.2014" ] }, "31.08.2014" ] },
"$$DESCEND",
"$$PRUNE"
]
}}
])
</code></pre>
<p>More modern, you would use <code>$filter</code>:</p>
<pre class="lang-js prettyprint-override"><code>db.products.aggregate([
{ "$match": { "items.date": "31.08.2014" } },
{ "$addFields": {
"items": {
"input": "$items",
"cond": { "$eq": [ "$$this.date", "31.08.2014" ] }
}
}}
])
</code></pre>
<p>And with multiple conditions, the <code>$elemMatch</code> and <code>$and</code> within the <code>$filter</code>:</p>
<pre class="lang-js prettyprint-override"><code>db.products.aggregate([
{ "$match": {
"$elemMatch": { "date": "31.08.2014", "purchasePrice": 1 }
}},
{ "$addFields": {
"items": {
"input": "$items",
"cond": {
"$and": [
{ "$eq": [ "$$this.date", "31.08.2014" ] },
{ "$eq": [ "$$this.purchasePrice", 1 ] }
]
}
}
}}
])
</code></pre>
<p>So it just depends on whether you always expect a single element to match or multiple elements, and then which approach is better. But where possible the <code>.find()</code> method will generally be faster since it lacks the overhead of the other operations, which in those last to forms does not lag that far behind at all.</p>
<p>As a side note, your "dates" are represented as strings which is not a very good idea going forward. Consider changing these to proper <a href="http://docs.mongodb.org/manual/reference/bson-types/#date" rel="noreferrer"><strong>Date</strong></a> object types, which will greatly help you in the future.</p> |
36,368,919 | Scrollable image with pinch-to-zoom in react-native | <p>I'm trying to display an image in my React Native app (Android) and I want to give users an ability to zoom that image in and out.
This also requires the image to be scrollable once zoomed in.</p>
<p>How would I go about it?</p>
<p>I tried to use <code>ScrollView</code> to display a bigger image inside, but on Android it can either scroll vertically or horizontally, not both ways.
Even if that worked there is a problem of making <code>pinch-to-zoom</code> work.</p>
<p>As far as I understand I need to use <code>PanResponder</code> on a custom view to zoom an image and position it accordingly. Is there an easier way?</p> | 37,449,923 | 7 | 3 | null | 2016-04-02 03:43:00.773 UTC | 18 | 2022-06-28 19:58:47.76 UTC | 2019-12-10 12:36:25.967 UTC | null | 10,496,406 | null | 219,449 | null | 1 | 26 | react-native | 42,166 | <p>I ended up rolling my own <code>ZoomableImage</code> component. So far it's been working out pretty well, here is the code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { Component } from "react";
import { View, PanResponder, Image } from "react-native";
import PropTypes from "prop-types";
function calcDistance(x1, y1, x2, y2) {
const dx = Math.abs(x1 - x2);
const dy = Math.abs(y1 - y2);
return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
}
function calcCenter(x1, y1, x2, y2) {
function middle(p1, p2) {
return p1 > p2 ? p1 - (p1 - p2) / 2 : p2 - (p2 - p1) / 2;
}
return {
x: middle(x1, x2),
y: middle(y1, y2)
};
}
function maxOffset(offset, windowDimension, imageDimension) {
const max = windowDimension - imageDimension;
if (max >= 0) {
return 0;
}
return offset < max ? max : offset;
}
function calcOffsetByZoom(width, height, imageWidth, imageHeight, zoom) {
const xDiff = imageWidth * zoom - width;
const yDiff = imageHeight * zoom - height;
return {
left: -xDiff / 2,
top: -yDiff / 2
};
}
class ZoomableImage extends Component {
constructor(props) {
super(props);
this._onLayout = this._onLayout.bind(this);
this.state = {
zoom: null,
minZoom: null,
layoutKnown: false,
isZooming: false,
isMoving: false,
initialDistance: null,
initialX: null,
initalY: null,
offsetTop: 0,
offsetLeft: 0,
initialTop: 0,
initialLeft: 0,
initialTopWithoutZoom: 0,
initialLeftWithoutZoom: 0,
initialZoom: 1,
top: 0,
left: 0
};
}
processPinch(x1, y1, x2, y2) {
const distance = calcDistance(x1, y1, x2, y2);
const center = calcCenter(x1, y1, x2, y2);
if (!this.state.isZooming) {
const offsetByZoom = calcOffsetByZoom(
this.state.width,
this.state.height,
this.props.imageWidth,
this.props.imageHeight,
this.state.zoom
);
this.setState({
isZooming: true,
initialDistance: distance,
initialX: center.x,
initialY: center.y,
initialTop: this.state.top,
initialLeft: this.state.left,
initialZoom: this.state.zoom,
initialTopWithoutZoom: this.state.top - offsetByZoom.top,
initialLeftWithoutZoom: this.state.left - offsetByZoom.left
});
} else {
const touchZoom = distance / this.state.initialDistance;
const zoom =
touchZoom * this.state.initialZoom > this.state.minZoom
? touchZoom * this.state.initialZoom
: this.state.minZoom;
const offsetByZoom = calcOffsetByZoom(
this.state.width,
this.state.height,
this.props.imageWidth,
this.props.imageHeight,
zoom
);
const left =
this.state.initialLeftWithoutZoom * touchZoom + offsetByZoom.left;
const top =
this.state.initialTopWithoutZoom * touchZoom + offsetByZoom.top;
this.setState({
zoom,
left:
left > 0
? 0
: maxOffset(left, this.state.width, this.props.imageWidth * zoom),
top:
top > 0
? 0
: maxOffset(top, this.state.height, this.props.imageHeight * zoom)
});
}
}
processTouch(x, y) {
if (!this.state.isMoving) {
this.setState({
isMoving: true,
initialX: x,
initialY: y,
initialTop: this.state.top,
initialLeft: this.state.left
});
} else {
const left = this.state.initialLeft + x - this.state.initialX;
const top = this.state.initialTop + y - this.state.initialY;
this.setState({
left:
left > 0
? 0
: maxOffset(
left,
this.state.width,
this.props.imageWidth * this.state.zoom
),
top:
top > 0
? 0
: maxOffset(
top,
this.state.height,
this.props.imageHeight * this.state.zoom
)
});
}
}
_onLayout(event) {
const layout = event.nativeEvent.layout;
if (
layout.width === this.state.width &&
layout.height === this.state.height
) {
return;
}
const zoom = layout.width / this.props.imageWidth;
const offsetTop =
layout.height > this.props.imageHeight * zoom
? (layout.height - this.props.imageHeight * zoom) / 2
: 0;
this.setState({
layoutKnown: true,
width: layout.width,
height: layout.height,
zoom,
offsetTop,
minZoom: zoom
});
}
componentWillMount() {
this._panResponder = PanResponder.create({
onStartShouldSetPanResponder: () => true,
onStartShouldSetPanResponderCapture: () => true,
onMoveShouldSetPanResponder: () => true,
onMoveShouldSetPanResponderCapture: () => true,
onPanResponderGrant: () => {},
onPanResponderMove: evt => {
const touches = evt.nativeEvent.touches;
if (touches.length === 2) {
this.processPinch(
touches[0].pageX,
touches[0].pageY,
touches[1].pageX,
touches[1].pageY
);
} else if (touches.length === 1 && !this.state.isZooming) {
this.processTouch(touches[0].pageX, touches[0].pageY);
}
},
onPanResponderTerminationRequest: () => true,
onPanResponderRelease: () => {
this.setState({
isZooming: false,
isMoving: false
});
},
onPanResponderTerminate: () => {},
onShouldBlockNativeResponder: () => true
});
}
render() {
return (
<View
style={this.props.style}
{...this._panResponder.panHandlers}
onLayout={this._onLayout}
>
<Image
style={{
position: "absolute",
top: this.state.offsetTop + this.state.top,
left: this.state.offsetLeft + this.state.left,
width: this.props.imageWidth * this.state.zoom,
height: this.props.imageHeight * this.state.zoom
}}
source={this.props.source}
/>
</View>
);
}
}
ZoomableImage.propTypes = {
imageWidth: PropTypes.number.isRequired,
imageHeight: PropTypes.number.isRequired,
source: PropTypes.object.isRequired
};
export default ZoomableImage;</code></pre>
</div>
</div>
</p> |
4,641,169 | Apple-like scrollbars using CSS | <p>I have noticed on some Apple sites like: <a href="http://help.apple.com/mobileme/index.html#mm5b08c671" rel="noreferrer">http://help.apple.com/mobileme/index.html#mm5b08c671</a> they have custom scrollbars using the WebKit scrollbar CSS stuff that recently came out. However I am unable to replicate it at all. Any ideas how to do it? I have a test site here but I get the default scrollbars? Thanks</p>
<p>Test: <a href="http://driz.co.uk/scrollbar/" rel="noreferrer">http://driz.co.uk/scrollbar/</a></p> | 4,641,257 | 1 | 1 | null | 2011-01-09 19:16:31.563 UTC | 12 | 2013-08-03 01:06:45.697 UTC | null | null | null | null | 302,533 | null | 1 | 17 | css|browser-scrollbars | 44,388 | <p>The following CSS monster is what Apple is using:</p>
<p><a href="http://jsfiddle.net/thirtydot/kTsUc/886/" rel="noreferrer">http://jsfiddle.net/thirtydot/kTsUc/886/</a></p>
<pre class="lang-css prettyprint-override"><code>::-webkit-scrollbar {
width: 15px;
height: 15px;
}
::-webkit-scrollbar-corner {
background-image: url(http://i.stack.imgur.com/FguQn.png?corner.png);
background-repeat: no-repeat;
}
::-webkit-resizer {
background-image: url(http://i.stack.imgur.com/aKKDY.png?resizer.png);
background-repeat: no-repeat;
background-position: bottom right;
}
::-webkit-scrollbar-button:start {
display: none;
}
::-webkit-scrollbar-button:end {
display: block;
}
::-webkit-scrollbar:horizontal {
-webkit-border-image: url(http://i.stack.imgur.com/NQ2K6.png?horizontal-button.png) 0 2 0 2;
border-color: transparent;
border-width: 0 2px;
background-image: url(http://i.stack.imgur.com/8xDbU.png?horizontal-button-background.png);
background-repeat: repeat-x;
}
::-webkit-scrollbar:horizontal:corner-present {
border-right-width: 0;
}
::-webkit-scrollbar-thumb:horizontal {
-webkit-border-image: url(http://i.stack.imgur.com/YQRD7.png?horizontal-thumb.png) 0 15 0 15;
border-color: transparent;
border-width: 0 15px;
min-width: 20px;
}
::-webkit-scrollbar-track-piece:horizontal:start {
margin-left: 6px;
}
::-webkit-scrollbar-track-piece:horizontal:end {
margin-right: -6px;
}
::-webkit-scrollbar-track-piece:horizontal:decrement {
-webkit-border-image: url(http://i.stack.imgur.com/p9yMk.png?horizontal-track.png) 0 15 0 15;
border-color: transparent;
border-width: 0 0 0 15px;
}
::-webkit-scrollbar-track-piece:horizontal:increment {
-webkit-border-image: url(http://i.stack.imgur.com/p9yMk.png?horizontal-track.png) 0 15 0 15;
border-color: transparent;
border-width: 0 15px 0 0;
}
::-webkit-scrollbar-button:horizontal {
width: 21px;
-webkit-border-image: url(http://i.stack.imgur.com/NQ2K6.png?horizontal-button.png) 0 2 0 2;
border-color: transparent;
border-width: 0 2px;
}
::-webkit-scrollbar-button:horizontal:decrement {
background-image: url(http://i.stack.imgur.com/dGOKL.png?horizontal-decrement-arrow.png), url(http://i.stack.imgur.com/8xDbU.png?horizontal-button-background.png);
background-repeat: no-repeat, repeat-x;
background-position: 7px 4px, 0 0;
}
::-webkit-scrollbar-button:horizontal:decrement:active {
-webkit-border-image: url(http://i.stack.imgur.com/gT5BM.png?horizontal-button-active.png) 0 2 0 2;
background-image: url(http://i.stack.imgur.com/dGOKL.png?horizontal-decrement-arrow.png), url(http://i.stack.imgur.com/RDf8L.png?horizontal-button-background-active.png);
}
::-webkit-scrollbar-button:horizontal:increment {
background-image: url(http://i.stack.imgur.com/5rJr5.png?horizontal-increment-arrow.png), url(http://i.stack.imgur.com/8xDbU.png?horizontal-button-background.png);
background-repeat: no-repeat, repeat-x;
width: 16px;
border-left-width: 0;
background-position: 3px 4px, 0 0;
}
::-webkit-scrollbar-button:horizontal:increment:active {
-webkit-border-image: url(http://i.stack.imgur.com/gT5BM.png?horizontal-button-active.png) 0 2 0 2;
background-image: url(http://i.stack.imgur.com/5rJr5.png?horizontal-increment-arrow.png), url(http://i.stack.imgur.com/RDf8L.png?horizontal-button-background-active.png);
}
::-webkit-scrollbar-button:horizontal:end:increment:corner-present {
border-right-width: 0;
width: 15px;
}
::-webkit-scrollbar:vertical {
-webkit-border-image: url(http://i.stack.imgur.com/NdaTT.png?vertical-button.png) 2 0 2 0;
border-color: transparent;
border-width: 2px 0;
background-image: url(http://i.stack.imgur.com/p7j9a.png?vertical-button-background.png);
background-repeat: repeat-y;
}
::-webkit-scrollbar:vertical:corner-present {
border-bottom-width: 0;
}
::-webkit-scrollbar-thumb:vertical {
-webkit-border-image: url(http://i.stack.imgur.com/rPEsZ.png?vertical-thumb.png) 15 0 15 0;
border-color: transparent;
border-width: 15px 0;
min-height: 20px;
}
::-webkit-scrollbar-track-piece:vertical:start {
margin-top: 6px;
}
::-webkit-scrollbar-track-piece:vertical:end {
margin-bottom: -6px;
}
::-webkit-scrollbar-track-piece:vertical:decrement {
-webkit-border-image: url(http://i.stack.imgur.com/Rb6ru.png?vertical-track.png) 15 0 15 0;
border-color: transparent;
border-width: 15px 0 0 0;
}
::-webkit-scrollbar-track-piece:vertical:increment {
-webkit-border-image: url(http://i.stack.imgur.com/Rb6ru.png?vertical-track.png) 15 0 15 0;
border-color: transparent;
border-width: 0 0 15px 0;
}
::-webkit-scrollbar-button:vertical {
height: 21px;
-webkit-border-image: url(http://i.stack.imgur.com/NdaTT.png?vertical-button.png) 2 0 2 0;
border-color: transparent;
border-width: 2px 0;
}
::-webkit-scrollbar-button:vertical:decrement {
background-image: url(http://i.stack.imgur.com/KQvwk.png?vertical-decrement-arrow.png), url(http://i.stack.imgur.com/p7j9a.png?vertical-button-background.png);
background-repeat: no-repeat, repeat-y;
background-position: 4px 7px, 0 0;
}
::-webkit-scrollbar-button:vertical:decrement:active {
-webkit-border-image: url(http://i.stack.imgur.com/uW3TL.png?vertical-button-active.png) 2 0 2 0;
background-image: url(http://i.stack.imgur.com/KQvwk.png?vertical-decrement-arrow.png), url(http://i.stack.imgur.com/puDsH.png?vertical-button-background-active.png);
}
::-webkit-scrollbar-button:vertical:increment {
background-image: url(http://i.stack.imgur.com/UjkVR.png?vertical-increment-arrow.png), url(http://i.stack.imgur.com/p7j9a.png?vertical-button-background.png);
background-repeat: no-repeat, repeat-y;
height: 16px;
border-top-width: 0;
background-position: 4px 5px, 0 0;
}
::-webkit-scrollbar-button:vertical:increment:active {
-webkit-border-image: url(http://i.stack.imgur.com/uW3TL.png?vertical-button-active.png) 2 0 2 0;
background-image: url(http://i.stack.imgur.com/UjkVR.png?vertical-increment-arrow.png), url(http://i.stack.imgur.com/puDsH.png?vertical-button-background-active.png);
}
::-webkit-scrollbar-button:vertical:end:increment:corner-present {
border-bottom-width: 0;
height: 15px;
}
::-webkit-scrollbar:disabled {
background: red;
-webkit-border-image: none;
display: none;
}
</code></pre>
<p>Some useful blog posts:</p>
<ul>
<li><a href="http://webkit.org/blog/363/styling-scrollbars/" rel="noreferrer">http://webkit.org/blog/363/styling-scrollbars/</a></li>
<li><a href="http://web.archive.org/web/20120115134443/http://numerosign.com/notebook/styling-webkit-scrollbars-with-css3/" rel="noreferrer">http://web.archive.org/web/20120115134443/http://numerosign.com/notebook/styling-webkit-scrollbars-with-css3/</a></li>
<li><a href="http://almaer.com/blog/creating-custom-scrollbars-with-css-how-css-isnt-great-for-every-task" rel="noreferrer">http://almaer.com/blog/creating-custom-scrollbars-with-css-how-css-isnt-great-for-every-task</a></li>
</ul> |
39,674,713 | Neural Network LSTM input shape from dataframe | <p>I am trying to implement an <a href="https://keras.io/layers/recurrent/#lstm" rel="noreferrer">LSTM with Keras</a>.</p>
<p>I know that LSTM's in Keras require a 3D tensor with shape <code>(nb_samples, timesteps, input_dim)</code> as an input. However, I am not entirely sure how the input should look like in my case, as I have just one sample of <code>T</code> observations for each input, not multiple samples, i.e. <code>(nb_samples=1, timesteps=T, input_dim=N)</code>. Is it better to split each of my inputs into samples of length <code>T/M</code>? <code>T</code> is around a few million observations for me, so how long should each sample in that case be, i.e., how would I choose <code>M</code>?</p>
<p>Also, am I right in that this tensor should look something like:</p>
<pre><code>[[[a_11, a_12, ..., a_1M], [a_21, a_22, ..., a_2M], ..., [a_N1, a_N2, ..., a_NM]],
[[b_11, b_12, ..., b_1M], [b_21, b_22, ..., b_2M], ..., [b_N1, b_N2, ..., b_NM]],
...,
[[x_11, x_12, ..., a_1M], [x_21, x_22, ..., x_2M], ..., [x_N1, x_N2, ..., x_NM]]]
</code></pre>
<p>where M and N defined as before and x corresponds to the last sample that I would have obtained from splitting as discussed above? </p>
<p>Finally, given a pandas dataframe with <code>T</code> observations in each column, and <code>N</code> columns, one for each input, how can I create such an input to feed to Keras?</p> | 40,005,797 | 2 | 2 | null | 2016-09-24 09:21:49.35 UTC | 33 | 2018-05-02 09:48:08.977 UTC | 2018-05-02 09:48:08.977 UTC | null | 7,483,494 | null | 2,151,205 | null | 1 | 41 | python|pandas|keras|lstm | 28,728 | <p>Below is an example that sets up time series data to train an LSTM. The model output is nonsense as I only set it up to demonstrate how to build the model.</p>
<pre><code>import pandas as pd
import numpy as np
# Get some time series data
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/timeseries.csv")
df.head()
</code></pre>
<p>Time series dataframe:</p>
<pre><code>Date A B C D E F G
0 2008-03-18 24.68 164.93 114.73 26.27 19.21 28.87 63.44
1 2008-03-19 24.18 164.89 114.75 26.22 19.07 27.76 59.98
2 2008-03-20 23.99 164.63 115.04 25.78 19.01 27.04 59.61
3 2008-03-25 24.14 163.92 114.85 27.41 19.61 27.84 59.41
4 2008-03-26 24.44 163.45 114.84 26.86 19.53 28.02 60.09
</code></pre>
<p>You can build put inputs into a vector and then use pandas <code>.cumsum()</code> function to build the sequence for the time series:</p>
<pre><code># Put your inputs into a single list
df['single_input_vector'] = df[input_cols].apply(tuple, axis=1).apply(list)
# Double-encapsulate list so that you can sum it in the next step and keep time steps as separate elements
df['single_input_vector'] = df.single_input_vector.apply(lambda x: [list(x)])
# Use .cumsum() to include previous row vectors in the current row list of vectors
df['cumulative_input_vectors'] = df.single_input_vector.cumsum()
</code></pre>
<p>The output can be set up in a similar way, but it will be a single vector instead of a sequence:</p>
<pre><code># If your output is multi-dimensional, you need to capture those dimensions in one object
# If your output is a single dimension, this step may be unnecessary
df['output_vector'] = df[output_cols].apply(tuple, axis=1).apply(list)
</code></pre>
<p>The input sequences have to be the same length to run them through the model, so you need to pad them to be the max length of your cumulative vectors:</p>
<pre><code># Pad your sequences so they are the same length
from keras.preprocessing.sequence import pad_sequences
max_sequence_length = df.cumulative_input_vectors.apply(len).max()
# Save it as a list
padded_sequences = pad_sequences(df.cumulative_input_vectors.tolist(), max_sequence_length).tolist()
df['padded_input_vectors'] = pd.Series(padded_sequences).apply(np.asarray)
</code></pre>
<p>Training data can be pulled from the dataframe and put into numpy arrays. <strong>Note that the input data that comes out of the dataframe will not make a 3D array. It makes an array of arrays, which is not the same thing.</strong></p>
<p>You can use hstack and reshape to build a 3D input array.</p>
<pre><code># Extract your training data
X_train_init = np.asarray(df.padded_input_vectors)
# Use hstack to and reshape to make the inputs a 3d vector
X_train = np.hstack(X_train_init).reshape(len(df),max_sequence_length,len(input_cols))
y_train = np.hstack(np.asarray(df.output_vector)).reshape(len(df),len(output_cols))
</code></pre>
<p>To prove it:</p>
<pre><code>>>> print(X_train_init.shape)
(11,)
>>> print(X_train.shape)
(11, 11, 6)
>>> print(X_train == X_train_init)
False
</code></pre>
<p>Once you have training data you can define the dimensions of your input layer and output layers.</p>
<pre><code># Get your input dimensions
# Input length is the length for one input sequence (i.e. the number of rows for your sample)
# Input dim is the number of dimensions in one input vector (i.e. number of input columns)
input_length = X_train.shape[1]
input_dim = X_train.shape[2]
# Output dimensions is the shape of a single output vector
# In this case it's just 1, but it could be more
output_dim = len(y_train[0])
</code></pre>
<p>Build the model:</p>
<pre><code>from keras.models import Model, Sequential
from keras.layers import LSTM, Dense
# Build the model
model = Sequential()
# I arbitrarily picked the output dimensions as 4
model.add(LSTM(4, input_dim = input_dim, input_length = input_length))
# The max output value is > 1 so relu is used as final activation.
model.add(Dense(output_dim, activation='relu'))
model.compile(loss='mean_squared_error',
optimizer='sgd',
metrics=['accuracy'])
</code></pre>
<p>Finally you can train the model and save the training log as history:</p>
<pre><code># Set batch_size to 7 to show that it doesn't have to be a factor or multiple of your sample size
history = model.fit(X_train, y_train,
batch_size=7, nb_epoch=3,
verbose = 1)
</code></pre>
<p>Output:</p>
<pre><code>Epoch 1/3
11/11 [==============================] - 0s - loss: 3498.5756 - acc: 0.0000e+00
Epoch 2/3
11/11 [==============================] - 0s - loss: 3498.5755 - acc: 0.0000e+00
Epoch 3/3
11/11 [==============================] - 0s - loss: 3498.5757 - acc: 0.0000e+00
</code></pre>
<p>That's it. Use <code>model.predict(X)</code> where <code>X</code> is the same format (other than the number of samples) as <code>X_train</code> in order to make predictions from the model.</p> |
6,403,091 | Stackpanel: Height vs ActualHeight vs ExtentHeight vs ViewportHeight vs DesiredSize vs RenderSize | <p>i want to know the height of all items my <code>StackPanel</code>. </p>
<p>What is the difference between:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.height.aspx"><code>Height</code></a> - Gets or sets the suggested height of the element. </li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.actualheight.aspx"><code>ActualHeight</code></a> - Gets the rendered height of this element. (<em>readonly</em>)</li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.stackpanel.extentheight.aspx"><code>ExtentHeight</code></a> - Gets a value that contains the vertical size of the extent. (<em>readonly</em>)</li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.stackpanel.viewportheight.aspx"><code>ViewportHeight</code></a> - Gets a value that contains the vertical size of the content's viewport. (<em>readonly</em>)</li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.windows.uielement.desiredsize.aspx"><code>DesiredSize</code></a> - Gets the size that this element computed during the measure pass of the layout process. (<em>readonly</em>)</li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.windows.uielement.rendersize.aspx"><code>RenderSize</code></a> - Gets (or sets, but see Remarks) the final render size of this element.</li>
</ul>
<hr>
<p>From MSDN:</p>
<blockquote>
<p><strong><a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.height.aspx">Height</a></strong><br>
Gets or sets the suggested height of the element. </p>
<p>Property value: <code>Double</code> - The height of the element, in device-independent units (1/96th inch per unit).</p>
<p>The height of the element, in device-independent units (1/96th inch per unit).</p>
</blockquote>
<p> </p>
<blockquote>
<p><strong><a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.actualheight.aspx">ActualHeight</a></strong> (<em>readonly</em>)<br>
Gets the rendered height of this element. </p>
<p>Property value: <code>Double</code> - The element's height, as a value in device-independent units (1/96th inch per unit). </p>
<p>This property is a calculated value based on other height inputs, and the layout system. The value is set by the layout system itself, based on an actual rendering pass, and may therefore lag slightly behind the set value of properties such as <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.height.aspx">Height</a> that are the basis of the input change.</p>
<p>Because ActualHeight is a calculated value, you should be aware that there could be multiple or incremental reported changes to it as a result of various operations by the layout system. The layout system may be calculating required measure space for child elements, constraints by the parent element, and so on.</p>
</blockquote>
<p> </p>
<blockquote>
<p><strong><a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.stackpanel.extentheight.aspx">ExtentHeight</a></strong> (<em>readonly</em>)<br>
Gets a value that contains the vertical size of the extent. </p>
<p>Property height: <code>Double</code> - A Double that represents the vertical size of the extent.</p>
<p>The returned value is described in Device Independent Pixels.</p>
</blockquote>
<p> </p>
<blockquote>
<p><strong><a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.stackpanel.viewportheight.aspx">ViewportHeight</a></strong> (<em>readonly</em>)<br>
Gets a value that contains the vertical size of the content's viewport.</p>
<p>Property value: <code>Double</code> - The Double that represents the vertical size of the content's viewport. </p>
<p>The returned value is described in Device Independent Pixels.</p>
</blockquote>
<p> </p>
<blockquote>
<p><strong><a href="http://msdn.microsoft.com/en-us/library/system.windows.uielement.desiredsize.aspx">DesiredSize</a></strong> (<em>readonly</em>)<br>
Gets the size that this element computed during the measure pass of the layout process.</p>
<p>Property value: <code>Size</code> - The computed size, which becomes the desired size for the arrange pass.</p>
<p>The value returned by this property will only be a valid measurement if the value of the IsMeasureValid property is true.</p>
<p>DesiredSize is typically checked as one of the measurement factors when you implement layout behavior overrides such as ArrangeOverride, MeasureOverride, or OnRender (in the OnRender case, you might check RenderSize instead, but this depends on your implementation). Depending on the scenario, DesiredSize might be fully respected by your implementation logic, constraints on DesiredSize might be applied, and such constraints might also change other characteristics of either the parent element or child element. For example, a control that supports scrollable regions (but chooses not to derive from the WPF framework-level controls that already enable scrollable regions) could compare available size to DesiredSize. The control could then set an internal state that enabled scrollbars in the UI for that control. Or, DesiredSize could potentially also be ignored in certain scenarios.</p>
</blockquote>
<p> </p>
<blockquote>
<p><strong><a href="http://msdn.microsoft.com/en-us/library/system.windows.uielement.rendersize.aspx">RenderSize</a></strong>
Gets the final render size of this element.</p>
<p>Property value: <code>Size</code> - The rendered size for this element.</p>
<p>This property can be used for checking the applicable render size within layout system overrides such as OnRender or GetLayoutClip.</p>
<p>A more common scenario is handling the SizeChanged event with the class handler override or the OnRenderSizeChanged event.</p>
</blockquote>
<hr>
<p>In my case i want know the <strong>desired</strong> height of all items in the <code>StackPanel</code>.</p>
<p>In other words: i want to know height of all items in the StackPanel (before drawing), and if they were to overflow the panel, i will </p>
<ul>
<li>delete</li>
<li>shrink</li>
<li>scale</li>
<li>adjust</li>
</ul>
<p>items to ensure they fit in the <strong>StackPanel</strong>.</p>
<p>Which means i probably want to get the <em>desired</em> height (ExtentHeight? DesiredSize?) during a <em>resize</em> event (<a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.sizechanged.aspx">SizeChanged</a>? <a href="http://msdn.microsoft.com/en-us/library/system.windows.uielement.layoutupdated.aspx">LayoutUpdated</a>? ) - before any drawing happens (so it's faster).</p>
<p>Most of these properties return zero; so obviously there's some understanding of what these properties mean that i don't know and are not explained in the documentation.</p> | 6,404,615 | 2 | 0 | null | 2011-06-19 14:48:41.83 UTC | 11 | 2014-02-12 03:17:53.873 UTC | 2013-06-16 00:25:07.09 UTC | null | 305,637 | null | 12,597 | null | 1 | 26 | wpf|layout|height|scaling|stackpanel | 21,925 | <p>As you know the <code>StackPanel</code> is a [Panel] object. Each panel communicates with its children by two methods to determine the final sizes and positions.
The first method is <code>MeasureOverride</code> and the second is <code>ArrangeOverride</code>.</p>
<p>The <code>MeasureOveride</code> asks each child for desired size with a given amount of space available.
<code>ArrangeOverride</code> arranges the children after measurement has been completed.</p>
<p>Let's create a stackpanel:</p>
<pre><code>public class AnotherStackPanel : Panel
{
public static readonly DependencyProperty OrientationProperty =
DependencyProperty.Register(“Orientation”, typeof(Orientation),
typeof(SimpleStackPanel), new FrameworkPropertyMetadata(
Orientation.Vertical, FrameworkPropertyMetadataOptions.AffectsMeasure));
public Orientation Orientation
{
get { return (Orientation)GetValue(OrientationProperty); }
set { SetValue(OrientationProperty, value); }
}
protected override Size MeasureOverride(Size availableSize)
{
Size desiredSize = new Size();
if (Orientation == Orientation.Vertical)
availableSize.Height = Double.PositiveInfinity;
else
availableSize.Width = Double.PositiveInfinity;
foreach (UIElement child in this.Children)
{
if (child != null)
{
child.Measure(availableSize);
if (Orientation == Orientation.Vertical)
{
desiredSize.Width = Math.Max(desiredSize.Width,
child.DesiredSize.Width);
desiredSize.Height += child.DesiredSize.Height;
}
else
{
desiredSize.Height = Math.Max(desiredSize.Height,
child.DesiredSize.Height);
desiredSize.Width += child.DesiredSize.Width;
}
}
}
return desiredSize;
}
protected override Size ArrangeOverride(Size finalSize)
{
double offset = 0;
foreach (UIElement child in this.Children)
{
if (child != null)
{
if (Orientation == Orientation.Vertical)
{
child.Arrange(new Rect(0, offset, finalSize.Width,
child.DesiredSize.Height));
offset += child.DesiredSize.Height;
}
else
{
child.Arrange(new Rect(offset, 0, child.DesiredSize.Width,
finalSize.Height));
offset += child.DesiredSize.Width;
}
}
}
return finalSize;
}
}
</code></pre>
<ul>
<li><p>The <code>DesiredSize</code> (the size
returned by <code>MeasureOverride</code>) is sum
of child sizes in the direction of
StackPanel and the size of largest
child in the other direction.</p></li>
<li><p><code>RenderSize</code> represents the final
size of the <code>StackPanel</code> after layout
is complete.</p></li>
<li><code>ActualHeight</code> is exactly same as
<code>RenderSize.Height</code>.</li>
</ul>
<p>For rely these properties you should access them only within an event handler for <a href="http://msdn.microsoft.com/en-us/library/system.windows.uielement.layoutupdated.aspx" rel="noreferrer">LayoutUpdated</a> event. </p>
<ul>
<li>for <code>ViewPortHeight</code> <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.scrollviewer.viewportheight.aspx" rel="noreferrer">look
here</a></li>
<li>for <code>ExtentHeight</code> <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.scrollviewer.extentheight.aspx" rel="noreferrer">look
here</a></li>
</ul> |
7,895,205 | Creating dropdown <select><option> elements with javascript | <p>I am new to jQuery and Javascript. I have to create select->option drop down control with client side jQuery/Javascripting. These drop downs are having their options from array and i have to create as many drop down as the array items. Please below two functions written, they are not drawing many drop downs but only one.</p>
<pre><code><script type="text/javascript">
// program inputs
var format1Fields = ",RepID,RetailOutlet,Address,Information,City,State,ZipCode, Demographic,Bullet,Date,Note1,Note2,Note3,Note4,Note5,AssignTask1,AssignTask2,AssignTask3,AssignTask4,LiquorPresence,PhotoLink1,Description1,PhotoLink2,Description2,PhotoLink3,Description3,PhotoLink4,Description4,PhotoLink5,Description5,PhotoLink6,Description6,PhotoLink7,Description7,PhotoLink8,Description8,PhotoLink9,Description9,PhotoLink10,Description10,PhotoLink11,Description11,PhotoLink12,Description12,Videolink1,Videodescription1,Videolink2,Videodescription2,Videolink3,Videodescription3,Videolink4,Videodescription4,POSInstalled1, POSQuantity1,POSInstalled2,POSQuantity2,POSInstalled3,POSQuantity3,POSInstalled4,POSQuantity4,POSInstalled5,POSQuantity5, POSInstalled6,POSQuantity6,POSInstalled7,POSQuantity7,POSInstalled8,POSQuantity8,POSInstalled9,POSQuantity9,POSInstalled10, POSQuantity10,POSInstalled11,POSQuantity11,POSInstalled12,POSQuantity12,Project,Visit,";
var outputFieldsString = "date visited,Mapping link,Date,RepID,Project,RetailOutLet,Address,City,State,Information,Demographic,Bullet,Note1,Note2,Note3,Note4,Note5,AssignTask1,AssignTask2,Assigntask3,AssignTask4,LiquorPresence,PhotoLink1,Picture01,Description1,PhotoLink2,Picture02,Description2,PhotoLink3,Picture03,Description3,PhotoLink4,Picture04,Description4,PhotoLink5,Picture05,Description5,PhotoLink6,Picture06,Description6,PhotoLink7,Picture07,Description7,PhotoLink8,Picture08,Description8,PosInstalled1,MC Cold Box Sticker,PosInstalled2,MC Poster 12 X 18,PosInstalled3,MC Poster 18 X 24,PosInstalled4,MC Poster 24 X 36,PosInstalled5,MC Case Cards,PosInstalled6,MC Standees,PosInstalled7,GM Poster 11 X 17,PosInstalled8,GM Poster 18 X 24,PosInstalled9,GM Recipe Table Tent,Photolink9,Description9,Photolink10,Description10,Photolink11,Description11,Photolink12,POSInstalled10,GM Shelf talker,POSInstalled11,GM Case Cards,POSInstalled12,GM Standees,Picture09,Picture10,Picture11,Picture12,Description12";
var outputDelimiter = ",";
var inputFieldList = new Array();
var outputFieldList = new Array();
$(document).ready(function(){
//$('#inputfields').val(trimOnSides(format1Fields.replace(' /g',''),","));
$('#inputfields').val(trimOnSides(format1Fields,","));
// start mapping click event
$('#start_mapping').click(function(){
var inputFieldString = $('#inputfields').val();
var inputDelimiter = $('#delimiter option:selected').val();
// input field validation
if(inputFieldString == ""){
alert("Please provide Input Fields header line having delimeter to identify the field names!");
$('#inputfields').focus();
return false;
}
// delimiter validation
if(inputDelimiter == "0"){
alert("Please select the correct delimiter that is matches with the seperating delimiter of the Input Fields!");
return false;
}
// Load input fields item array
inputFieldList = getFieldsList(inputFieldString,inputDelimiter);
if(inputFieldList.length==0){
alert("Problem transforming Input Field data into list of items for mapping");
return false;
}
// Load output fields item array
outputFieldList = getFieldsList(outputFieldsString,outputDelimiter);
if(outputFieldList.length==0){
alert("Problem transforming Output Field data into list of items for mapping");
return false;
}
// print field list item in HTML <ol>
getFormListItems(inputFieldList);
//getDropDownList('waqas','aiseha',inputFieldList);
});
});
// ###### HELPER FUNCTIONS #######
// helper to generate form of drop down
function getFormListItems(fieldListItems){
if((fieldListItems instanceof Array) && (fieldListItems.length>0)){
var list = $('#mappingitems').append('<ul></ul>').find('ul');
for(i=0; i<=fieldListItems.length-1; i++){
list.append('<li>');
list.append(getDropDownList(fieldListItems[i],fieldListItems[i],fieldListItems));
list.append('</li>');
//list.append('<li>'+fieldListItems[i]+'</li>');
//alert(i);
}
}
}
function getDropDownList(name, id, optionList) {
var combo = $("<select></select>").attr("name", name);
$.each(optionList, function (i, el) {
combo.append("<option>" + el + "</option>");
});
return combo;
// OR
//$("#SELECTOR").append(combo);
}
// helper split based string array generators
function getFieldsList(fieldsString, delimiter){
var returnList = new Array();
//alert(fieldsString);
// validating the arguments and their data type
if((fieldsString.length > 0) && (delimiter.length>0)){
returnList = fieldsString.split(delimiter);
return returnList;
}else{
alert('Problem in function arguments');
}
}
// helper string functions
function trimOnSides(str, chars) {
return ltrim(rtrim(str, chars), chars);
}
function ltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
</script>
</code></pre>
<p>this is the call to the function: getFormListItems(inputFieldList);
inputFieldList can contain Apple, Orange, Banana, Mango</p>
<p>Please help
thanks
Waqas</p> | 7,895,287 | 1 | 4 | null | 2011-10-25 20:07:20.323 UTC | 2 | 2012-11-09 14:36:31.333 UTC | 2012-11-09 14:36:31.333 UTC | null | 1,083,946 | null | 460,966 | null | 1 | 11 | javascript|jquery|html|dom|select | 47,250 | <p>This will create the drop downs on the fly:</p>
<pre><code>function getDropDownList(name, id, optionList) {
var combo = $("<select></select>").attr("id", id).attr("name", name);
$.each(optionList, function (i, el) {
combo.append("<option>" + el + "</option>");
});
return combo;
// OR
$("#SELECTOR").append(combo);
}
</code></pre> |
7,923,509 | How to include docs directory in python distribution | <p>I have a python project with the following structure:</p>
<pre><code>Clustering (project name)
clustering (package)
clustering.py and other modules
tests (sub-package)
test_clustering.py and other such files
docs/
bin/
</code></pre>
<p>I would like to include the docs directory in my distribution, but I can not seem to do that. Any pointers about how this can be done would be very helpful.</p>
<p>My current setup.py looks like this:</p>
<pre><code>from distutils.core import setup
setup(name='Clustering',
version='1.0',
description='desc',
author='A',
author_email='[email protected]',
packages=['clustering', 'clustering.tests'],
requires=['numpy', 'scipy'],
scripts=['bin/predict', 'bin/verify']
)
</code></pre>
<p>I tried using the package_data option but haven't been successful in including the docs directory in the distribution. Is there some other conventional way of including your docs in the distribution?</p> | 7,923,595 | 1 | 2 | null | 2011-10-27 23:12:11.963 UTC | 7 | 2018-02-14 17:51:50.8 UTC | 2018-02-14 17:51:50.8 UTC | null | 387,648 | null | 387,648 | null | 1 | 29 | python|setup.py | 14,513 | <p>You'll need to create a MANIFEST.in file and include some simple instructions on what extra files you want to include (See <a href="http://docs.python.org/distutils/sourcedist.html#the-manifest-in-template" rel="noreferrer">MANIFEST.in Template</a>)</p>
<p>Example (to include docs dir and all files directly underneath):</p>
<pre><code>include docs/*
</code></pre>
<p>or, to include all files in the doc dir (recursively):</p>
<pre><code>recursive-include docs *
</code></pre> |
8,132,868 | Mercurial: How to restore after rebase | <p>I've accidentally pulled some changes from the main repo with --rebase parameter.</p>
<p>How do I restore the original repository state from the backup which was created during the rebase?</p> | 8,133,527 | 1 | 0 | null | 2011-11-15 07:27:54.627 UTC | 6 | 2012-11-12 06:30:29.867 UTC | 2012-11-12 06:30:29.867 UTC | null | 905,318 | null | 905,318 | null | 1 | 30 | mercurial|backup|restore|rebase | 10,889 | <p><code>hg unbundle</code> is used to apply the backup file:</p>
<pre><code>hg unbundle .hg/strip-backup/e64394fd5837-backup.hg
</code></pre>
<p>However, this does not remove the new changesets that have been created by the rebase; it is probably a good idea to call <code>hg unbundle</code> from a repo that does not have the rebased changesets (i.e. clone latest version from server).</p> |
21,422,548 | How to select the Date Picker In Selenium WebDriver | <p>Currently working on <strong>Selenium WebDriver</strong> and using <strong>Java</strong>. I want to select values in <code>date range</code> from the drop down.. I want to know how can I select the values as <code>Date, Month and year</code> in the date picker drop down.</p>
<p>Here is the HTML tag:</p>
<pre><code><dd id="date-element">
<input id="fromDate" class="hasDatepicker" type="text" style="width:57px; padding:3px 1px; font-size:11px;" readonly="readonly" name="fromDate" value="01 Jan 2013">
<input id="toDate" class="hasDatepicker" type="text" style="width:57px; padding:3px 1px; font-size:11px;" readonly="readonly" name="toDate" value="31 Dec 2013">
</code></pre>
<p><img src="https://i.stack.imgur.com/xvfrp.jpg" alt="enter image description here"></p>
<p>The below sample code i tried:</p>
<pre><code>Log.info("Clicking on From daterange dropdown");
JavascriptExecutor executor8 = (JavascriptExecutor)driver;
executor8.executeScript("document.getElementById('fromDate').style.display='block';");
Select select8 = new Select(driver.findElement(By.id("fromDate")));
select8.selectByVisibleText("10 Jan 2013");
Thread.sleep(3000);
Log.info("Clicking on To daterange dropdown");
JavascriptExecutor executor10 = (JavascriptExecutor)driver;
executor10.executeScript("document.getElementById('toDate').style.display='block';");
Select select10 = new Select(driver.findElement(By.id("toDate")));
select10.selectByVisibleText("31 Dec 2013");
Thread.sleep(3000);
</code></pre> | 21,422,726 | 8 | 2 | null | 2014-01-29 05:06:41.277 UTC | 9 | 2020-07-13 17:58:54.93 UTC | 2014-05-29 07:11:29.917 UTC | null | 3,686,522 | null | 2,994,827 | null | 1 | 15 | java|jquery|selenium|selenium-webdriver | 141,173 | <p>DatePicker are not <code>Select</code> element. What your doing in your code is wrong. </p>
<p>Datepicker are in fact table with set of rows and columns.To select a date you just have to navigate to the cell where our desired date is present.</p>
<p>So your code should be like this:</p>
<pre><code>WebElement dateWidget = driver.findElement(your locator);
List<WebElement> columns=dateWidget.findElements(By.tagName("td"));
for (WebElement cell: columns){
//Select 13th Date
if (cell.getText().equals("13")){
cell.findElement(By.linkText("13")).click();
break;
}
</code></pre> |
21,803,522 | The server encountered an error processing the request. See server logs for more details | <p>I have a simple problem.</p>
<p>I've created a WCF Data Service 5.6 in visual studio 2013, and in its <code>*.svc.cs</code> file, modified line</p>
<pre><code>public class CustomdataService : DataService< /* TODO: put your data source class name here */ >
</code></pre>
<p>to connect my entities</p>
<pre><code>public class CustomdataService : DataService< SchedulerEntities >
</code></pre>
<p>But when I want to see the service in browser it gives me following error</p>
<blockquote>
<p>Request Error</p>
<p>The server encountered an error processing the request. See server logs for more details.</p>
</blockquote>
<p>The entity framework is nothing but a single table...</p> | 21,834,504 | 4 | 2 | null | 2014-02-15 20:54:28.563 UTC | 4 | 2018-12-20 03:18:12.647 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 2,529,670 | null | 1 | 25 | wcf|entity-framework | 45,449 | <p>It seems that Entity Framework 6 and WCF Data Services 5.6.0 need some provider to work together, read more on <a href="https://blogs.msdn.microsoft.com/odatateam/2013/10/02/using-wcf-data-services-5-6-0-with-entity-framework-6/" rel="nofollow noreferrer">Using WCF Data Services 5.6.0 with Entity Framework 6+</a>. </p>
<p>You can download the provider simply by using NuGet Package Console Manager:</p>
<pre><code>Install-Package Microsoft.OData.EntityFrameworkProvider -Pre
</code></pre>
<p>Its version is alpha 2, so in future, search for final release. it worked for me however.</p>
<p>Final thing is, instead of using <code>DataService<T></code>, you need to use <code>EntityFrameworkDataService<T></code>. <code>T</code> is the name of your entities.</p> |
1,788,779 | View the source of an R package | <p>Is there an easy way to view the source of an R package (or a method in a package), from within the interactive environment?</p> | 1,788,834 | 4 | 0 | null | 2009-11-24 08:58:44.593 UTC | 10 | 2018-10-17 22:36:37.883 UTC | 2012-10-12 18:50:19.28 UTC | null | 636,656 | null | 30,911 | null | 1 | 24 | r|r-faq | 15,004 | <p>Just enter the name of a function/method without parentheses:</p>
<pre><code>R> base::rev.default
function (x)
if (length(x)) x[length(x):1L] else x
<environment: namespace:base>
</code></pre>
<p>See also <em>R-Help Desk - Accessing the Sources</em> in <a href="http://www.r-project.org/doc/Rnews/Rnews_2006-4.pdf" rel="noreferrer">R News Volume 6/4, October 2006</a>.</p> |
2,276,349 | case-insensitive array_unique | <p>I'm trying to write a few lines of code to make a case insensitive array unique type function. Here's what I have so far:</p>
<pre><code>foreach ($topics as $value) {
$lvalue = strtolower($value);
$uvalue = strtolower($value);
if (in_array($value, $topics) == FALSE || in_array($lvalue, $topics) == FALSE || in_array($uvalue, $topics) == FALSE) {
array_push($utopics, $value);
}
}
</code></pre>
<p>The trouble is the if statement. I think there's something wrong with my syntax, but I'm relatively new to PHP and I'm not sure what it is. Any help?</p> | 2,276,400 | 4 | 0 | null | 2010-02-16 21:07:25.247 UTC | 7 | 2018-11-30 15:15:49.55 UTC | 2010-02-16 21:09:48.893 UTC | null | 68,587 | null | 218,913 | null | 1 | 35 | php|arrays|loops|foreach | 14,768 | <pre><code>function array_iunique( $array ) {
return array_intersect_key(
$array,
array_unique( array_map( "strtolower", $array ) )
);
}
</code></pre> |
2,156,363 | How to filter the results of content resolver in android? | <p>I would like to get user contacts and then append some kind of regular expression and append them to a list view. I am currently able to get all the contacts via </p>
<p><code>getContentResolver().query(People.CONTENT_URI, null, null, null, null);</code> </p>
<p>and then pass them to a custom class that extends <code>SimpleCursorAdapter</code>.</p>
<p>So I would like to know how to get only the contacts that match a regular expression and not all of users contacts.</p> | 2,158,589 | 4 | 0 | null | 2010-01-28 17:03:35.503 UTC | 15 | 2017-03-22 10:35:18.787 UTC | 2012-05-21 02:50:20.347 UTC | null | 67,022 | null | 234,898 | null | 1 | 36 | android | 54,509 | <p>Instead of </p>
<pre><code>getContentResolver().query(People.CONTENT_URI, null, null, null, null);
</code></pre>
<p>you should use something like</p>
<pre><code>final ContentResolver resolver = getContentResolver();
final String[] projection = { People._ID, People.NAME, People.NUMBER };
final String sa1 = "%A%"; // contains an "A"
cursor = resolver.query(People.CONTENT_URI, projection, People.NAME + " LIKE ?",
new String[] { sa1 }, null);
</code></pre>
<p>this uses a parameterized request (using <strong>?</strong>) and provides the actual values as a different argument, this avoids concatenation and prevents <strong>SQL</strong> injection mainly if you are requesting the filter from the user. For example if you are using</p>
<pre><code>cursor = resolver.query(People.CONTENT_URI, projection,
People.NAME + " = '" + name + "'",
new String[] { sa1 }, null);
</code></pre>
<p>imagine if</p>
<pre><code>name = "Donald Duck' OR name = 'Mickey Mouse") // notice the " and '
</code></pre>
<p>and you are concatenating the strings.</p> |
1,384,006 | PHP: how to avoid redeclaring functions? | <p>I tend to get errors such as:</p>
<blockquote>
<p>Fatal error: Cannot redeclare get_raw_data_list() (previously declared in /var/www/codes/handlers/make_a_thread/get_raw_data_list.php:7) in /var/www/codes/handlers/make_a_thread/get_raw_data_list.php on line 19</p>
</blockquote>
<p>how can I avoid the error? Is it possible to create a IF-clause to check whether a function is declared before declaring it?</p> | 1,384,012 | 4 | 0 | null | 2009-09-05 18:46:48.74 UTC | 3 | 2017-02-17 23:24:42.397 UTC | 2017-02-17 23:24:42.397 UTC | null | 2,370,483 | null | 164,148 | null | 1 | 40 | php|function|declaration | 37,306 | <p>Use <a href="http://us2.php.net/manual/en/function.require-once.php" rel="noreferrer"><code>require_once</code></a> or <a href="http://us2.php.net/manual/en/function.include-once.php" rel="noreferrer"><code>include_once</code></a> as opposed to <a href="http://us2.php.net/manual/en/function.include.php" rel="noreferrer"><code>include</code></a> or <a href="http://us2.php.net/manual/en/function.require.php" rel="noreferrer"><code>require</code></a> when including the files that contain your functions.</p>
<p>The <em><code>_once</code></em> siblings of <code>include</code> and <code>require</code> will force PHP to check if the file has already been included/required, and if so, not <code>include</code>/<code>require</code> it again, thereby preventing '<em>cannot redeclare x function...</em>' fatal errors.</p> |
10,446,641 | In SQL, is it OK for two tables to refer to each other? | <p>In this system, we store products, images of products (there can be many image for a product), and a default image for a product. The database:</p>
<pre><code>CREATE TABLE `products` (
`ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`NAME` varchar(255) NOT NULL,
`DESCRIPTION` text NOT NULL,
`ENABLED` tinyint(1) NOT NULL DEFAULT '1',
`DATEADDED` datetime NOT NULL,
`DEFAULT_PICTURE_ID` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`ID`),
KEY `Index_2` (`DATEADDED`),
KEY `FK_products_1` (`DEFAULT_PICTURE_ID`),
CONSTRAINT `FK_products_1` FOREIGN KEY (`DEFAULT_PICTURE_ID`) REFERENCES `products_pictures` (`ID`) ON DELETE SET NULL ON UPDATE SET NULL
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8;
CREATE TABLE `products_pictures` (
`ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`IMG_PATH` varchar(255) NOT NULL,
`PRODUCT_ID` int(10) unsigned NOT NULL,
PRIMARY KEY (`ID`),
KEY `FK_products_pictures_1` (`PRODUCT_ID`),
CONSTRAINT `FK_products_pictures_1` FOREIGN KEY (`PRODUCT_ID`) REFERENCES `products` (`ID`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
</code></pre>
<p>as you can see, <code>products_pictures.PRODUCT_ID -> products.ID</code> and <code>products.DEFAULT_PICTURE_ID -> products_pictures.ID</code>, so a cycle reference. Is it OK?</p> | 10,458,105 | 6 | 2 | null | 2012-05-04 09:58:01.353 UTC | 23 | 2021-03-31 15:18:47.063 UTC | 2012-05-05 00:55:10.863 UTC | null | 11,343 | null | 1,043,342 | null | 1 | 46 | mysql|database|database-design | 25,778 | <p>No, it's not OK. Circular references between tables are messy. See this (decade old) article: <a href="https://www.itprotoday.com/sql-design-circular-reference" rel="noreferrer">SQL By Design: The Circular Reference</a></p>
<p>Some DBMS can handle these, and with special care, but MySQL will have issues.</p>
<hr />
<p><strong>Option 1</strong></p>
<p>As your design, to make one of the two FKs nullable. This allows you to solve the chicken-and-egg problem (which table should I first Insert into?).</p>
<p>There is a problem though with your code. It will allow a product to have a default picture where that picture will be referencing another product!</p>
<p>To disallow such an error, your FK constraint should be:</p>
<pre><code>CONSTRAINT FK_products_1
FOREIGN KEY (id, default_picture_id)
REFERENCES products_pictures (product_id, id)
ON DELETE RESTRICT --- the SET NULL options would
ON UPDATE RESTRICT --- lead to other issues
</code></pre>
<p>This will require a <code>UNIQUE</code> constraint/index in table <code>products_pictures</code> on <code>(product_id, id)</code> for the above FK to be defined and work properly.</p>
<hr />
<p><strong>Option 2</strong></p>
<p>Another approach is to remove the <code>Default_Picture_ID</code> column form the <code>product</code> table and add an <code>IsDefault BIT</code> column in the <code>picture</code> table. The problem with this solution is how to allow only one picture per product to have that bit on and all others to have it off. In SQL-Server (and I think in Postgres) this can be done with a partial index:</p>
<pre><code>CREATE UNIQUE INDEX is_DefaultPicture
ON products_pictures (Product_ID)
WHERE IsDefault = 1 ;
</code></pre>
<p>But MySQL has no such feature.</p>
<hr />
<p><strong>Option 3</strong></p>
<p>This approach, allows you to even have both FK columns defined as <code>NOT NULL</code> is to use deferrable constraints. This works in PostgreSQL and I think in Oracle. Check this question and the answer by @Erwin: <a href="https://stackoverflow.com/questions/8394177/complex-foreign-key-constraint-in-sqlalchemy/8395021#8395021">Complex foreign key constraint in SQLAlchemy</a> (the <strong>All key columns NOT NULL</strong> Part).</p>
<p>Constraints in MySQL cannot be deferrable.</p>
<hr />
<p><strong>Option 4</strong></p>
<p>The approach (which I find cleanest) is to remove the <code>Default_Picture_ID</code> column and add another table. No circular path in the FK constraints and all FK columns will be <code>NOT NULL</code> with this solution:</p>
<pre><code>product_default_picture
----------------------
product_id NOT NULL
default_picture_id NOT NULL
PRIMARY KEY (product_id)
FOREIGN KEY (product_id, default_picture_id)
REFERENCES products_pictures (product_id, id)
</code></pre>
<p>This will also require a <code>UNIQUE</code> constraint/index in table <code>products_pictures</code> on <code>(product_id, id)</code> as in solution 1.</p>
<hr />
<p><strong>To summarize, with MySQL you have two options:</strong></p>
<ul>
<li><p>option 1 (a nullable FK column) with the correction above to enforce integrity correctly</p>
</li>
<li><p>option 4 (no nullable FK columns)</p>
</li>
</ul> |
10,631,283 | How will i know whether inline function is actually replaced at the place where it is called or not? | <p>I know that inline function are either replaced where it is called or behave as a normal function.</p>
<p>But how will I know whether inline function is actually replaced at the place where it is called or not as decision of treating inline function as inline is at the compile time?</p> | 10,631,297 | 10 | 2 | null | 2012-05-17 07:02:10.3 UTC | 15 | 2020-06-12 11:58:51.103 UTC | null | null | null | null | 223,622 | null | 1 | 47 | c++|inline | 18,615 | <p>Programatically at run-time, You cannot.<br />
And the truth of the matter is: <em><strong>You don't need to know</strong></em></p>
<p>An compiler can choose to <code>inline</code> functions that are not marked <code>inline</code> or ignore functions marked explicitly <code>inline</code>, it is completely the wish(read <em>wisdom</em>) of the compiler & You should trust the compiler do its job judiciously. Most of the mainstream compilers will do their job nicely.</p>
<p>If your question is purely from a academic point of view then there are a couple of options available:</p>
<hr />
<h2>Analyze generated Assembly Code:</h2>
<p>You can check the assembly code to check if the function code is inlined at point of calling.</p>
<p><strong>How to generate the assembly code?</strong></p>
<p><strong>For gcc:</strong><br />
Use the <code>-S</code> switch while compilation.<br />
For ex:</p>
<pre><code>g++ -S FileName.cpp
</code></pre>
<p>The generated assembly code is created as file <code>FileName.s</code>.</p>
<p><strong>For MSVC:</strong><br />
Use the <strong><a href="http://msdn.microsoft.com/en-us/library/367y26c6.aspx" rel="noreferrer">/FA Switch</a></strong> from command line.</p>
<p>In the generated assembly code lookup if there is a <code>call</code> assembly instruction for the particular function.</p>
<hr />
<h2>Use Compiler specific Warnings and Diagnostics:</h2>
<p>Some compilers will emit a warning if they fail to comply an inline function request.<br />
For example, in gcc, the <code>-Winline</code> command option will emit a warning if the compiler does not inline a function that was declared inline.</p>
<p>Check the <strong><a href="http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html" rel="noreferrer">GCC documentation</a></strong> for more detail:</p>
<blockquote>
<p><strong>-Winline</strong></p>
<p>Warn if a function that is declared as inline cannot be inlined. Even with this option, the compiler does not warn about failures to inline functions declared in system headers.</p>
<p>The compiler uses a variety of heuristics to determine whether or not to inline a function. For example, the compiler takes into account the size of the function being inlined and the amount of inlining that has already been done in the current function. Therefore, seemingly insignificant changes in the source program can cause the warnings produced by <code>-Winline</code> to appear or disappear.</p>
</blockquote> |
10,462,819 | Get keys from HashMap in Java | <p>I have a Hashmap in Java like this:</p>
<pre><code>private Map<String, Integer> team1 = new HashMap<String, Integer>();
</code></pre>
<p>Then I fill it like this:</p>
<pre><code>team1.put("United", 5);
</code></pre>
<p>How can I get the keys? Something like: <code>team1.getKey()</code> to return "United".</p> | 10,462,838 | 15 | 2 | null | 2012-05-05 14:32:18.983 UTC | 36 | 2021-09-28 09:57:41.37 UTC | 2019-03-30 01:46:27.933 UTC | null | 201,359 | null | 455,946 | null | 1 | 214 | java|data-structures|java-6 | 827,243 | <p>A <code>HashMap</code> contains more than one key. You can use <code>keySet()</code> to get the set of all keys.</p>
<pre><code>team1.put("foo", 1);
team1.put("bar", 2);
</code></pre>
<p>will store <code>1</code> with key <code>"foo"</code> and <code>2</code> with key <code>"bar"</code>. To iterate over all the keys:</p>
<pre><code>for ( String key : team1.keySet() ) {
System.out.println( key );
}
</code></pre>
<p>will print <code>"foo"</code> and <code>"bar"</code>.</p> |
59,409,664 | (x | y) - y why can't it simply be x or even `x | 0` | <p>I was reading a kernel code, and in one place I've seen an expression inside <code>if</code> statement like</p>
<pre><code>if (value == (SPINLOCK_SHARED | 1) - 1) {
............
}
</code></pre>
<p>where <code>SPINLOCK_SHARED = 0x80000000</code> is a predefined constant. </p>
<p>I wonder why do we need <code>(SPINLOCK_SHARED | 1) - 1</code> - for type conversion purpose? the result of the expression would be 80000000-- same as 0x80000000, is it not? yet, why ORing 1 and Subtracting 1 matters?</p>
<p>Have a feeling like I am missing to get something..</p> | 59,973,634 | 6 | 13 | null | 2019-12-19 12:17:44.723 UTC | 5 | 2020-01-29 18:44:35.05 UTC | 2019-12-19 12:43:10.63 UTC | null | 5,198,101 | null | 5,198,101 | null | 1 | 47 | c|bit-manipulation | 3,874 | <p>It was just done that way for clarity, that's all. It's because atomic_fetchadd_int() (in e.g. sys/spinlock2.h) returns the value PRIOR to the addition/subtraction, and that value is passed to _spin_lock_contested()</p>
<p>Note that the C compiler completely pre-calculates all constant expressions. In fact, the compiler can even optimize-out inlined code based on conditionals that use passed-in procedure arguments when the procedures are passed constants in those arguments. This is why the lockmgr() inline in sys/lock.h has a case statement.... because that entire case statement will be optimized out and devolve into a direct call to the appropriate function.</p>
<p>Also, in all of these locking functions the overhead of the atomic ops dwarf all other calculations by two or three orders of magnitude.</p>
<p>-Matt</p> |
7,646,766 | Set Linear layout background dynamically | <p>I wanted to set Linear Layout background dynamically in the following way:</p>
<ol>
<li><p>Fetch image from web url through XML parsing and then store that image into sd card.</p></li>
<li><p>Now the image saved into sd card.</p></li>
<li><p>Set that image as a linear layout background in the app.</p></li>
</ol>
<p>Now I am stuck in the third step. Can anyone help?</p> | 7,646,910 | 7 | 1 | null | 2011-10-04 10:53:27.453 UTC | 3 | 2018-01-23 09:36:46 UTC | 2013-05-29 18:28:16.037 UTC | null | 264,775 | null | 960,526 | null | 1 | 19 | android|android-layout|android-widget | 54,613 | <p>Use this:</p>
<pre><code>Bitmap bmImg = BitmapFactory.decodeStream(is);
BitmapDrawable background = new BitmapDrawable(bmImg);
linearLayout.setBackgroundDrawable(background);
</code></pre>
<p>Also check this: <a href="https://stackoverflow.com/questions/2415619/how-to-convert-a-bitmap-to-drawable-in-android">How to convert a Bitmap to Drawable in android?</a></p> |
14,015,592 | How to create a new unknown or dynamic/expando object in Python | <p>In python how can we create a new object without having a predefined Class and later dynamically add properties to it ?</p>
<p>example: </p>
<pre><code>dynamic_object = Dynamic()
dynamic_object.dynamic_property_a = "abc"
dynamic_object.dynamic_property_b = "abcdefg"
</code></pre>
<p>What is the best way to do it?</p>
<p><strong>EDIT</strong> Because many people advised in comments that I might not need this. </p>
<p>The thing is that I have a function that serializes an object's properties. For that reason, I don't want to create an object of the expected class due to some constructor restrictions, but instead create a similar one, let's say like a <strong>mock</strong>, add any "custom" properties I need, then feed it back to the function.</p> | 14,015,611 | 7 | 2 | null | 2012-12-23 23:41:47.167 UTC | 9 | 2021-08-11 00:12:00.69 UTC | 2014-02-26 23:50:19.58 UTC | null | 1,857,292 | null | 1,857,292 | null | 1 | 45 | python|oop|class|object|expandoobject | 38,225 | <p>Just define your own class to do it:</p>
<pre><code>class Expando(object):
pass
ex = Expando()
ex.foo = 17
ex.bar = "Hello"
</code></pre> |
43,074,659 | React-Native: Avoid Text Wrapping | <p>I have the title of a song and its duration showing in one line. The song title needs to show an ellipsis but the duration should never wrap or show ellipsis. I've tried several combinations but fail to make this work right for long titles. The duration either goes off screen when the name shows ellipsis or the duration wraps. I can't hardcode a fixed width on the duration as it can change size.</p>
<pre><code><View style={{flexDirection: 'row'}}>
<Text numberOfLines={2} style={{fontSize: 16, textAlign: 'left'}}>{title}</Text>
<Text style={{flex: 1, fontSize: 13, textAlign: 'right', marginTop: 2}}>{duration}</Text>
</View>
</code></pre> | 43,099,012 | 2 | 2 | null | 2017-03-28 16:11:24.157 UTC | 1 | 2021-09-29 12:23:40.797 UTC | 2021-09-06 17:10:45.013 UTC | null | 2,037,924 | null | 5,822,695 | null | 1 | 36 | javascript|react-native|layout|flexbox | 40,407 | <p>The solution ended up being fairly simple. Not entirely intuitive but here's how to solve this. It appears that the text that needs ellipsis requires <code>flex: 1</code>.</p>
<pre><code> <View style={{ flexDirection: "row" }}>
<Text numberOfLines={1} style={{ flex: 1, textAlign: "left" }}>
{title}
</Text>
<Text style={{ textAlign: "right" }}>{duration}</Text>
</View>;
</code></pre> |
24,627,522 | Protect ArrayList from write access | <p>Consider the following class: </p>
<pre><code>public class Cars extends Observable{
private ArrayList<String> carList = new ArrayList<String>();
public void addToCarList(String car){
// ...
hasChanged();
notifyObservers();
}
public void removeFromCarList(String car){
// ...
hasChanged();
notifyObservers();
}
public ArrayList<String> getCarList() {
return carList;
}
}
</code></pre>
<p>As you can see, every time the carList is changed, I want to notify the <code>Observers</code>.
If someone does <code>getCarList().add(...);</code>, this is circumvented. </p>
<p>How can I give read access to the <code>carList</code> (for iterating over it etc.) but prevent write access to it except for the special methods <code>addToCarList</code> and <code>removeFromCarList</code>? </p>
<p>I thought about this: </p>
<pre><code>public ArrayList<String> getCarList() {
return (ArrayList<String>)carList.clone();
}
</code></pre>
<p>but someone using my class would, when adding something to the clone of <code>carList</code>, not be informed that that's not the way it's meant to be done. </p> | 24,627,605 | 5 | 3 | null | 2014-07-08 08:51:44.257 UTC | 1 | 2014-07-09 01:36:45.987 UTC | null | null | null | null | 804,967 | null | 1 | 31 | java | 4,278 | <p>You can return an unmodifiable view of it, changing the return type to <code>List<String></code> instead of <code>ArrayList<String></code>:</p>
<pre><code>public List<String> getCars() {
return Collections.unmodifiableList(carList);
}
</code></pre>
<p>Note that as <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableList-java.util.List-" rel="noreferrer"><code>Collections.unmodifiableList</code></a> <em>does</em> only provide a view, the caller will still see any other changes that are made via <code>addToCarList</code> and <code>removeFromCarList</code> (which I'd rename to <code>addCar</code> and <code>removeCar</code>, probably). Is that what you want?</p>
<p>Any mutating operations on the returned view will result in an <code>UnsupportedOperationException</code>.</p> |
228,783 | What are the rules about using an underscore in a C++ identifier? | <p>It's common in C++ to name member variables with some kind of prefix to denote the fact that they're member variables, rather than local variables or parameters. If you've come from an MFC background, you'll probably use <code>m_foo</code>. I've also seen <code>myFoo</code> occasionally.</p>
<p>C# (or possibly just .NET) seems to recommend using just an underscore, as in <code>_foo</code>. Is this allowed by the C++ standard?</p> | 228,797 | 5 | 2 | null | 2008-10-23 07:02:06.347 UTC | 433 | 2020-04-19 17:11:31.09 UTC | 2019-02-25 13:39:55.363 UTC | null | 2,370,483 | Roger Lipscombe | 8,446 | null | 1 | 1,019 | c++|naming-conventions|standards|c++-faq | 312,645 | <p>The rules (which did not change in C++11):</p>
<ul>
<li>Reserved in any scope, including for use as <a href="https://stackoverflow.com/questions/4297933/c-implementation#4297974">implementation</a> macros:
<ul>
<li>identifiers beginning with an underscore followed immediately by an uppercase letter</li>
<li>identifiers containing adjacent underscores (or "double underscore")</li>
</ul></li>
<li>Reserved in the global namespace:
<ul>
<li>identifiers beginning with an underscore</li>
</ul></li>
<li>Also, everything in the <code>std</code> namespace is reserved. (You are allowed to add template specializations, though.) </li>
</ul>
<p>From the 2003 C++ Standard:</p>
<blockquote>
<h3>17.4.3.1.2 Global names [lib.global.names]</h3>
<p>Certain sets of names and function signatures are always reserved to the implementation:</p>
<ul>
<li>Each name that contains a double underscore (<code>__</code>) or begins with an underscore followed by an uppercase letter (2.11) is reserved to the implementation for any use.</li>
<li>Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.<sup>165</sup></li>
</ul>
<p><sup>165)</sup> Such names are also reserved in namespace <code>::std</code> (17.4.3.1). </p>
</blockquote>
<p>Because C++ is based on the C standard (1.1/2, C++03) and C99 is a normative reference (1.2/1, C++03) these also apply, from the 1999 C Standard:</p>
<blockquote>
<h3>7.1.3 Reserved identifiers</h3>
<p>Each header declares or defines all identifiers listed in its associated subclause, and
optionally declares or defines identifiers listed in its associated future library directions subclause and identifiers which are always reserved either for any use or for use as file scope identifiers.</p>
<ul>
<li>All identifiers that begin with an underscore and either an uppercase letter or another
underscore are always reserved for any use.</li>
<li>All identifiers that begin with an underscore are always reserved for use as identifiers
with file scope in both the ordinary and tag name spaces.</li>
<li>Each macro name in any of the following subclauses (including the future library
directions) is reserved for use as specified if any of its associated headers is included;
unless explicitly stated otherwise (see 7.1.4).</li>
<li>All identifiers with external linkage in any of the following subclauses (including the
future library directions) are always reserved for use as identifiers with external
linkage.<sup>154</sup></li>
<li>Each identifier with file scope listed in any of the following subclauses (including the
future library directions) is reserved for use as a macro name and as an identifier with
file scope in the same name space if any of its associated headers is included.</li>
</ul>
<p>No other identifiers are reserved. If the program declares or defines an identifier in a
context in which it is reserved (other than as allowed by 7.1.4), or defines a reserved
identifier as a macro name, the behavior is undefined.</p>
<p>If the program removes (with <code>#undef</code>) any macro definition of an identifier in the first
group listed above, the behavior is undefined.</p>
<p><sup>154)</sup> The list of reserved identifiers with external linkage includes <code>errno</code>, <code>math_errhandling</code>, <code>setjmp</code>, and <code>va_end</code>.</p>
</blockquote>
<p>Other restrictions might apply. For example, the POSIX standard reserves a lot of identifiers that are likely to show up in normal code:</p>
<ul>
<li>Names beginning with a capital <code>E</code> followed a digit or uppercase letter:
<ul>
<li>may be used for additional error code names.</li>
</ul></li>
<li>Names that begin with either <code>is</code> or <code>to</code> followed by a lowercase letter
<ul>
<li>may be used for additional character testing and conversion functions.</li>
</ul></li>
<li>Names that begin with <code>LC_</code> followed by an uppercase letter
<ul>
<li>may be used for additional macros specifying locale attributes.</li>
</ul></li>
<li>Names of all existing mathematics functions suffixed with <code>f</code> or <code>l</code> are reserved
<ul>
<li>for corresponding functions that operate on float and long double arguments, respectively.</li>
</ul></li>
<li>Names that begin with <code>SIG</code> followed by an uppercase letter are reserved
<ul>
<li>for additional signal names.</li>
</ul></li>
<li>Names that begin with <code>SIG_</code> followed by an uppercase letter are reserved
<ul>
<li>for additional signal actions.</li>
</ul></li>
<li>Names beginning with <code>str</code>, <code>mem</code>, or <code>wcs</code> followed by a lowercase letter are reserved
<ul>
<li>for additional string and array functions.</li>
</ul></li>
<li>Names beginning with <code>PRI</code> or <code>SCN</code> followed by any lowercase letter or <code>X</code> are reserved
<ul>
<li>for additional format specifier macros</li>
</ul></li>
<li>Names that end with <code>_t</code> are reserved
<ul>
<li>for additional type names.</li>
</ul></li>
</ul>
<p>While using these names for your own purposes right now might not cause a problem, they do raise the possibility of conflict with future versions of that standard.</p>
<hr>
<p>Personally I just don't start identifiers with underscores. New addition to my rule: Don't use double underscores anywhere, which is easy as I rarely use underscore.</p>
<p>After doing research on this article I no longer end my identifiers with <code>_t</code>
as this is reserved by the POSIX standard.</p>
<p>The rule about any identifier ending with <code>_t</code> surprised me a lot. I think that is a POSIX standard (not sure yet) looking for clarification and official chapter and verse. This is from the <a href="http://www.gnu.org/software/libtool/manual/libc/Reserved-Names.html" rel="noreferrer">GNU libtool manual</a>, listing reserved names.</p>
<p>CesarB provided the following link to the <a href="http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_02.html" rel="noreferrer">POSIX 2004</a> reserved symbols and notes 'that many other reserved prefixes and suffixes ... can be found there'. The
<a href="http://www.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html" rel="noreferrer">POSIX 2008</a> reserved symbols are defined here. The restrictions are somewhat more nuanced than those above.</p> |
772,608 | jQuery loop through data() object | <p>Is it possible to loop through a <code>data()</code> object?</p>
<p>Suppose this is my code:</p>
<pre><code>$('#mydiv').data('bar','lorem');
$('#mydiv').data('foo','ipsum');
$('#mydiv').data('cam','dolores');
</code></pre>
<p>How do I loop through this? Can <code>each()</code> be used for this?</p> | 772,676 | 6 | 0 | null | 2009-04-21 13:32:55.153 UTC | 12 | 2017-04-10 04:33:18.863 UTC | 2015-11-04 15:21:55.643 UTC | null | 4,370,109 | null | 78,297 | null | 1 | 25 | jquery|loops|each | 41,076 | <p>jQuery stores all the data information in the jQuery.cache internal variable. It is possible to get all the data associated with a particular object with this simple but helpful plugin:</p>
<pre><code>jQuery.fn.allData = function() {
var intID = jQuery.data(this.get(0));
return(jQuery.cache[intID]);
};
</code></pre>
<p>With this in place, you can do this:</p>
<pre><code>$('#myelement').data('test1','yay1')
.data('test2','yay2')
.data('test3','yay3');
$.each($('#myelement').allData(), function(key, value) {
alert(key + "=" + value);
});
</code></pre>
<p>You could just use matt b's suggestion but this is how to do it with what you have right now.</p> |
280,559 | How to get cmd line build command for VS solution? | <p>This is probably easy but I am getting stuck: when I build a solution in Visual Studio - how do extract the exact cmd line for the current build command in order to be able to do the same build from VisualStudio console? </p>
<p>In the output window I can see the single projects in the solution build commands but not the one for the whole solution.</p>
<p>I am on VS2005.</p>
<p>Any help would be appreciated</p> | 280,584 | 6 | 0 | null | 2008-11-11 10:41:37.32 UTC | 12 | 2013-02-07 10:25:58.167 UTC | null | null | null | JohnIdol | 1,311,500 | null | 1 | 29 | visual-studio|command-line|build-process | 67,536 | <p>In addition to what @JohnIdol says correctly, I've found that you need to setup a number VS environment variables. I don't have the name of the batch file in front of me, but you can modify or 'I think' use it. It is in VS program files tree somewhere. Also, as I remember you don't want to be in a standard shell but a .NET setup shell for some paths and such. I'll add details later when I'm at a Windows PC with VS.</p>
<p>EDIT: The batch file mentioned is a shortcut in ProgFiles menu. Here is the details of its properties. </p>
<pre><code>%comspec% /k ""C:\Program Files\Microsoft Visual Studio 8\VC\vcvarsall.bat""x86"
</code></pre>
<p>Here is my batch file, using MSBuild to call the solution.</p>
<pre><code>@echo off
:: setup VS2005 command line build environment
set VSINSTALLDIR=C:\Program Files\Microsoft Visual Studio 8
set VCINSTALLDIR=C:\Program Files\Microsoft Visual Studio 8\VC
set FrameworkDir=C:\WINDOWS\Microsoft.NET\Framework
set FrameworkVersion=v2.0.50727
set FrameworkSDKDir=C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0
set DevEnvDir=C:\Program Files\Microsoft Visual Studio 8\Common7\IDE
set PATH=C:\Program Files\Microsoft Visual Studio 8\Common7\IDE;C:\Program Files\Microsoft Visual Studio 8\VC\BIN;C:\Program Files\Microsoft Visual Studio 8\Com
mon7\Tools;C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\bin;C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\bin;C:\Program Files\Microsoft
Visual Studio 8\SDK\v2.0\bin;C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727;C:\Program Files\Microsoft Visual Studio 8\VC\VCPackages;%PATH%
set INCLUDE=C:\Program Files\Microsoft Visual Studio 8\VC\ATLMFC\INCLUDE;C:\Program Files\Microsoft Visual Studio 8\VC\INCLUDE;C:\Program Files\Microsoft Visual
Studio 8\VC\PlatformSDK\include;C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\include;%INCLUDE%
set LIB=C:\Program Files\Microsoft Visual Studio 8\VC\ATLMFC\LIB;C:\Program Files\Microsoft Visual Studio 8\VC\LIB;C:\Program Files\Microsoft Visual Studio 8\VC
\PlatformSDK\lib;C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\lib;%LIB%
set LIBPATH=C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727;C:\Program Files\Microsoft Visual Studio 8\VC\ATLMFC\LIB
echo %0 %*
echo %0 %* >> %MrB-LOG%
cd
if not ""=="%~dp1" pushd %~dp1
cd
if exist %~nx1 (
echo VS2005 build of '%~nx1'.
echo VS2005 build of '%~nx1'. >> %MrB-LOG%
set MrB-BUILDLOG=%MrB-BASE%\%MrB-WORK%.%MrB-NICEDATE%.%MrB-NICETIME%.build-errors.log
msbuild.exe %~nx1 /t:Rebuild /p:Configuration=Release > %MrB-BUILDLOG%
findstr /r /c:"[1-9][0-9]* Error(s)" %MrB-BUILDLOG%
if not errorlevel 1 (
echo ERROR: sending notification email for build errors in '%~nx1'.
echo ERROR: sending notification email for build errors in '%~nx1'. >> %MrB-LOG%
call mrb-email "Mr Build isn't happy about build errors in '%~nx1'" %MrB-BUILDLOG%
) else (
findstr /r /c:"[1-9][0-9]* Warning(s)" %MrB-BUILDLOG%
if not errorlevel 1 (
echo ERROR: sending notification email for build warnings in '%~nx1'.
echo ERROR: sending notification email for build warnings in '%~nx1'. >> %MrB-LOG%
call mrb-email "Mr Build isn't happy about build warnings in '%~nx1'" %MrB-BUILDLOG%
) else (
echo Successful build of '%~nx1'.
echo Successful build of '%~nx1'. >> %MrB-LOG%
)
)
) else (
echo ERROR '%1' doesn't exist.
echo ERROR '%1' doesn't exist. >> %MrB-LOG%
)
popd
</code></pre> |
1,234,750 | C++ Socket Server - Unable to saturate CPU | <p>I've developed a mini HTTP server in C++, using boost::asio, and now I'm load testing it with multiple clients and I've been unable to get close to saturating the CPU. I'm testing on a Amazon EC2 instance, and getting about 50% usage of one cpu, 20% of another, and the remaining two are idle (according to htop).</p>
<p>Details:</p>
<ul>
<li>The server fires up one thread per core</li>
<li>Requests are received, parsed, processed, and responses are written out</li>
<li>The requests are for data, which is read out of memory (read-only for this test)</li>
<li>I'm 'loading' the server using two machines, each running a java application, running 25 threads, sending requests</li>
<li>I'm seeing about 230 requests/sec throughput (this is <em>application</em> requests, which are composed of many HTTP requests)</li>
</ul>
<p>So, what should I look at to improve this result? Given the CPU is mostly idle, I'd like to leverage that additional capacity to get a higher throughput, say 800 requests/sec or whatever.</p>
<p>Ideas I've had:</p>
<ul>
<li>The requests are very small, and often fulfilled in a few ms, I could modify the client to send/compose bigger requests (perhaps using batching)</li>
<li>I could modify the HTTP server to use the Select design pattern, is this appropriate here?</li>
<li>I could do some profiling to try to understand what the bottleneck's are/is</li>
</ul> | 1,238,315 | 6 | 6 | null | 2009-08-05 17:56:43.947 UTC | 17 | 2016-06-19 12:14:09.057 UTC | 2012-02-20 14:31:06.67 UTC | null | 504,239 | null | 118,130 | null | 1 | 30 | c++|linux|multithreading|scalability|boost-asio | 14,403 | <p>boost::asio is not as thread-friendly as you would hope - there is a big lock around the epoll code in boost/asio/detail/epoll_reactor.hpp which means that only one thread can call into the kernel's epoll syscall at a time. And for very small requests this makes all the difference (meaning you will only see roughly single-threaded performance).</p>
<p>Note that this is a limitation of how boost::asio uses the Linux kernel facilities, not necessarily the Linux kernel itself. The epoll syscall does support multiple threads when using edge-triggered events, but getting it right (without excessive locking) can be quite tricky.</p>
<p>BTW, I have been doing some work in this area (combining a fully-multithreaded edge-triggered epoll event loop with user-scheduled threads/fibers) and made some code available under the <a href="http://nginetd.cmeerw.org" rel="noreferrer">nginetd</a> project.</p> |
31,087,111 | TypeError: 'list' object is not callable in python | <p>I am novice to Python and following a tutorial. There is an example of <code>list</code> in the tutorial :</p>
<pre><code>example = list('easyhoss')
</code></pre>
<p>Now, In tutorial, <code>example= ['e','a',...,'s']</code>. But in my case I am getting following error:</p>
<pre><code>>>> example = list('easyhoss')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
</code></pre>
<p>Please tell me where I am wrong. I searched SO <a href="https://stackoverflow.com/questions/5735841/python-typeerror-list-object-is-not-callable">this</a> but it is different.</p> | 31,087,151 | 13 | 3 | null | 2015-06-27 09:16:56.127 UTC | 23 | 2022-04-09 17:29:51.95 UTC | 2017-05-23 12:17:50.79 UTC | null | -1 | null | 4,770,390 | null | 1 | 90 | python|list | 506,212 | <p>Seems like you've shadowed the builtin name <code>list</code> pointing at a class by the same name pointing at its instance. Here is an example:</p>
<pre><code>>>> example = list('easyhoss') # here `list` refers to the builtin class
>>> list = list('abc') # we create a variable `list` referencing an instance of `list`
>>> example = list('easyhoss') # here `list` refers to the instance
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: 'list' object is not callable
</code></pre>
<p>I believe this is fairly obvious. Python stores object names (functions and classes are objects, too) in namespaces (which are implemented as dictionaries), hence you can rewrite pretty much any name in any scope. It won't show up as an error of some sort. As you might know, Python emphasizes that "special cases aren't special enough to break the rules". And there are two major rules behind the problem you've faced:</p>
<ol>
<li><p><em>Namespaces</em>. Python supports nested namespaces. Theoretically you can endlessly nest namespaces. As I've already mentioned, namespaces are basically dictionaries of names and references to corresponding objects. Any module you create gets its own "global" namespace. In fact it's just a local namespace with respect to that particular module.</p>
</li>
<li><p><em>Scoping</em>. When you reference a name, the Python runtime looks it up in the local namespace (with respect to the reference) and, if such name does not exist, it repeats the attempt in a higher-level namespace. This process continues until there are no higher namespaces left. In that case you get a <code>NameError</code>. Builtin functions and classes reside in a special high-order namespace <code>__builtins__</code>. If you declare a variable named <code>list</code> in your module's global namespace, the interpreter will never search for that name in a higher-level namespace (that is <code>__builtins__</code>). Similarly, suppose you create a variable <code>var</code> inside a function in your module, and another variable <code>var</code> in the module. Then, if you reference <code>var</code> inside the function, you will never get the global <code>var</code>, because there is a <code>var</code> in the local namespace - the interpreter has no need to search it elsewhere.</p>
</li>
</ol>
<p>Here is a simple illustration.</p>
<pre><code>>>> example = list("abc") # Works fine
>>>
>>> # Creating name "list" in the global namespace of the module
>>> list = list("abc")
>>>
>>> example = list("abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
>>> # Python looks for "list" and finds it in the global namespace,
>>> # but it's not the proper "list".
>>>
>>> # Let's remove "list" from the global namespace
>>> del list
>>> # Since there is no "list" in the global namespace of the module,
>>> # Python goes to a higher-level namespace to find the name.
>>> example = list("abc") # It works.
</code></pre>
<p>So, as you see there is nothing special about Python builtins. And your case is a mere example of universal rules. You'd better use an IDE (e.g. a free version of PyCharm, or Atom with Python plugins) that highlights name shadowing to avoid such errors.</p>
<p>You might as well be wondering what is a "callable", in which case you can read <a href="https://stackoverflow.com/a/111255/3846213">this post</a>. <code>list</code>, being a class, is callable. Calling a class triggers instance construction and initialisation. An instance might as well be callable, but <code>list</code> instances are not. If you are even more puzzled by the distinction between classes and instances, then you might want to read <a href="https://docs.python.org/3/tutorial/classes.html" rel="noreferrer">the documentation</a> (quite conveniently, the same page covers namespaces and scoping).</p>
<p>If you want to know more about builtins, please read the <a href="https://stackoverflow.com/a/55115952/4518341">answer by Christian Dean</a>.</p>
<p><strong>P.S.</strong> When you start an interactive Python session, you create a temporary module.</p> |
70,446,275 | Failed to start DevTools: Dart DevTools exited with code 255 | <p>I am getting this error code in my Visual Studio Code. How can I fix it?</p>
<p>I am using Flutter v2.5.3.</p>
<p><img src="https://i.stack.imgur.com/nJy9U.png" alt="" /></p> | 70,447,455 | 8 | 3 | null | 2021-12-22 08:42:13.997 UTC | 8 | 2022-05-23 06:14:26.273 UTC | 2022-01-04 02:08:49.633 UTC | null | 63,550 | null | 10,498,695 | null | 1 | 45 | flutter | 12,073 | <p>You can try fixing it by running this in the terminal:</p>
<p>Just copy and paste the below code into the terminal and run it.</p>
<pre class="lang-none prettyprint-override"><code>dart pub global activate devtools -v 2.8.0
</code></pre>
<p>which downgrades the version to 2.8.0 (that works fine). I found the answer on <a href="https://github.com/flutter/devtools/issues/3549#issuecomment-998961200" rel="nofollow noreferrer">GitHub</a>.</p> |
17,958,288 | branch and checkout using a single command | <p>Creating and using a new branch involves two commands:</p>
<pre><code>$ git branch new_branch_name
$ git checkout new_branch_name
</code></pre>
<p>I tend to forget the latter, which can be annoying. Is there a way to do this using a single command? Perhaps using an alias, or something similar? I know I could write a shell function, but that seems a bit much work for such a simple and common task.</p>
<p>Bazaar does support this to some degree using the <code>bzr branch --switch</code> notation.</p> | 66,760,299 | 3 | 1 | null | 2013-07-30 22:05:29.813 UTC | 7 | 2022-09-14 06:27:01.647 UTC | null | null | null | null | 1,468,366 | null | 1 | 72 | git|version-control|git-branch|git-checkout | 15,481 | <p>Git introduced <code>switch</code> in version 2.23 to handle changing of branches specifically and avoid the use of <code>checkout</code> which can be confusing by the sheer amount of operations it can do.</p>
<p>Among other possibilites,</p>
<pre><code>git switch <branch> # to switch to an existing branch
git switch -c <new_branch> # to create a new branch and switch to it
</code></pre> |
17,905,827 | Why does my image have space underneath? | <p>Images gain a mysterious empty space underneath, even if <code>padding:0;margin:0</code> are applied.</p>
<p><a href="http://jsfiddle.net/cLETP/" rel="noreferrer">Demonstration</a></p>
<p><img src="https://i.imgur.com/Cnmpu1P.png" alt="screenshot"></p>
<p>The red border should hug the image, but there is space on the bottom side.</p>
<p>What causes this, and how can I remove this space?</p> | 17,905,828 | 3 | 1 | null | 2013-07-28 07:02:23.077 UTC | 18 | 2017-11-18 00:14:30.36 UTC | 2014-12-29 00:42:58.763 UTC | null | 507,674 | null | 507,674 | null | 1 | 42 | html|css|image | 5,836 | <p>Images (and inline-block elements in general) are treated like a character.</p>
<p>As such, they obey the rule of the baseline.</p>
<p>In normal text, the baseline is the line across the bottom of most letters, such as in this sentence.</p>
<p>But some letters, such as <code>p</code>, <code>q</code>, <code>j</code> and so on, have tails that drop below the baseline. In order to prevent these tails from colliding with letters on the next line, space is reserved between the baseline and the bottom line.</p>
<p>This diagram illustrates the different lines used by text:</p>
<p><a href="https://i.stack.imgur.com/d9KWH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/d9KWH.png" alt="WHATWG's baseline diagram"></a>
(Image from <a href="http://www.whatwg.org/" rel="noreferrer">WHATWG</a>)</p>
<p>So, the image is aligned to the baseline, even if there is no text. Fortunately, the fix is very simple:</p>
<pre><code>img {vertical-align:bottom}
</code></pre>
<p>This will align the image to the bottom of the line, also removing the mystery space.</p>
<p><em>Just be careful, if your image is small (smaller than the line height), you may start seeing mystery space appearing above the image instead. To fix this, add <code>line-height:1px</code> to the container element.</em></p>
<p>Hopefully this helps the many people I've seen ask about this and similar problems!</p> |
47,288,496 | Are there disadvantages in putting code into Userforms instead of modules? | <p><strong>Are there disadvantages in putting code into a VBA Userform instead of into a "normal" module?</strong></p>
<p>This might be a simple question but I have not found a conclusive answer to it while searching the web and stackoverflow. </p>
<p><strong>Background:</strong> I am developing a Front-End Application of a database in Excel-VBA. To select different filters I have different userforms. I ask what general program design is better: <strong>(1) putting the control structure into a separate module</strong> OR <strong>(2) putting the code for the next userform or action in the userform</strong>. </p>
<p>Lets make an example. I have a Active-X Button which triggers my filters and my forms.</p>
<p><strong>Variant1: Modules</strong></p>
<p>In the CommandButton:</p>
<pre><code>Private Sub CommandButton1_Click()
call UserInterfaceControlModule
End Sub
</code></pre>
<p>In the Module:</p>
<pre><code>Sub UserInterfaceControllModule()
Dim decisionInput1 As Boolean
Dim decisionInput2 As Boolean
UserForm1.Show
decisionInput1 = UserForm1.decision
If decisionInput1 Then
UserForm2.Show
Else
UserForm3.Show
End If
End Sub
</code></pre>
<p>In Variant 1 the control structure is in a normal module. And decisions about which userform to show next are separated from the userform. Any information needed to decide about which userform to show next has to be pulled from the userform.</p>
<p><strong>Variant2: Userform</strong></p>
<p>In the CommadButton:</p>
<pre><code>Private Sub CommandButton1_Click()
UserForm1.Show
End Sub
</code></pre>
<p>In Userform1:</p>
<pre><code>Private Sub ToUserform2_Click()
UserForm2.Show
UserForm1.Hide
End Sub
Private Sub UserForm_Click()
UserForm2.Show
UserForm1.Hide
End Sub
</code></pre>
<p>In Variant 2 the control structure is directly in the userforms and each userform has the instructions about what comes after it. </p>
<p>I have started development using method 2. If this was a mistake and there are some serious drawbacks to this method I want to know it rather sooner than later.</p> | 47,291,028 | 1 | 18 | null | 2017-11-14 14:41:03.833 UTC | 23 | 2019-02-26 04:58:11.61 UTC | 2019-02-26 04:58:11.61 UTC | null | 1,188,513 | null | 8,019,379 | null | 1 | 26 | excel|vba|user-interface|userform | 4,868 | <blockquote>
<p><strong>Disclaimer</strong> I wrote the <a href="https://rubberduckvba.wordpress.com/2017/10/25/userform1-show/" rel="noreferrer">article</a> Victor K <a href="https://stackoverflow.com/questions/47288496/are-there-disadvantages-in-putting-code-into-userforms-instead-of-modules#comment81527590_47288496">linked to</a>. I own that blog, and manage the open-source VBIDE add-in project it's for.</p>
</blockquote>
<p>Neither of your alternatives are ideal. Back to basics.</p>
<hr>
<blockquote>
<p><em>To select different filters I have differnt (sic) userforms.</em></p>
</blockquote>
<p>Your specifications demand that the user needs to be able to select different filters, and you chose to implement a UI for it using a <code>UserForm</code>. So far, so good... and it's all downhill from there.</p>
<p>Making the form responsible for anything other than <em>presentation concerns</em> is a common mistake, and it has a name: it's the <em>Smart UI</em> [anti-]pattern, and the problem with it is that <strong>it doesn't scale</strong>. It's great for prototyping (i.e. make a quick thing that "works" - note the scare quotes), not so much for anything that needs to be maintained over years.</p>
<p>You've probably seen these forms, with 160 controls, 217 event handlers, and 3 private procedures closing in on 2000 lines of code each: that's how badly <em>Smart UI</em> scales, and it's the only possible outcome down that road.</p>
<p>You see, a <code>UserForm</code> is a class module: it defines the <em>blueprint</em> of an <em>object</em>. Objects usually want to be <em>instantiated</em>, but then someone had the genius idea of granting all instances of <code>MSForms.UserForm</code> a <em>predeclared ID</em>, which in COM terms means you basically get a global object for free.</p>
<p>Great! No? No.</p>
<blockquote>
<pre><code>UserForm1.Show
decisionInput1 = UserForm1.decision
If decisionInput1 Then
UserForm2.Show
Else
UserForm3.Show
End If
</code></pre>
</blockquote>
<p>What happens if <code>UserForm1</code> is "X'd-out"? Or if <code>UserForm1</code> is <code>Unload</code>ed? If the form isn't handling its <code>QueryClose</code> event, the object is destroyed - but because that's the <em>default instance</em>, VBA automatically/silently creates a new one for you, just before your code reads <code>UserForm1.decision</code> - as a result you get whatever the initial global state is for <code>UserForm1.decision</code>.</p>
<p>If it wasn't a <em>default instance</em>, and <code>QueryClose</code> wasn't handled, then accessing the <code>.decision</code> member of a destroyed object would give you the classic run-time error 91 for accessing a null object reference.</p>
<p><code>UserForm2.Show</code> and <code>UserForm3.Show</code> both do the same thing: fire-and-forget - whatever happens happens, and to find out exactly what that consists of, you need to dig it up in the forms' respective code-behind.</p>
<p>In other words, the <strong>forms are running the show</strong>. They're responsible for collecting the data, presenting that data, collecting user input, <em>and doing whatever work needs to be done with it</em>. That's why it's called "Smart UI": the UI knows everything.</p>
<p>There's a better way. MSForms is the COM ancestor of .NET's WinForms UI framework, and what the ancestor has in common with its .NET successor, is that it works particularly well with the famous <em>Model-View-Presenter</em> (MVP) pattern.</p>
<hr>
<h3>The Model</h3>
<p>That's your <em>data</em>. Essentially, it's <em>what your application logic need to know</em> out of the form.</p>
<ul>
<li><code>UserForm1.decision</code> let's go with that.</li>
</ul>
<p>Add a new class, call it, say, <code>FilterModel</code>. Should be a very simple class:</p>
<pre><code>Option Explicit
Private Type TModel
SelectedFilter As String
End Type
Private this As TModel
Public Property Get SelectedFilter() As String
SelectedFilter = this.SelectedFilter
End Property
Public Property Let SelectedFilter(ByVal value As String)
this.SelectedFilter = value
End Property
Public Function IsValid() As Boolean
IsValid = this.SelectedFilter <> vbNullString
End Function
</code></pre>
<p>That's really all we need: a class to encapsulate the form's data. The class can be responsible for some validation logic, or whatever - but it doesn't <em>collect</em> the data, it doesn't <em>present</em> it to the user, and it doesn't <em>consume</em> it either. It <em>is</em> the data.</p>
<p>Here there's only 1 property, but you could have many more: think one field on the form => one property.</p>
<p>The model is also what the form needs to know from the application logic. For example if the form needs a drop-down that displays a number of possible selections, the model would be the object exposing them.</p>
<hr>
<h3>The View</h3>
<p>That's your form. It's responsible for knowing about controls, writing to and reading from the <em>model</em>, and... that's all. We're looking at a dialog here: we bring it up, user fills it up, closes it, and the program acts upon it - the form itself doesn't <em>do</em> anything with the data it collects. The model might validate it, the form might decide to disable its <kbd>Ok</kbd> button until the model says its data is valid and good to go, but <strong>under no circumstances</strong> a <code>UserForm</code> reads or writes from a worksheet, a database, a file, a URL, or anything.</p>
<p>The form's code-behind is dead simple: it wires up the UI with the model instance, and enables/disables its buttons as needed.</p>
<p>The important things to remember:</p>
<ul>
<li><code>Hide</code>, don't <code>Unload</code>: the view is an object, and objects don't self-destruct.</li>
<li><strong>NEVER</strong> refer to the form's <em>default instance</em>.</li>
<li>Always handle <code>QueryClose</code>, again, to avoid a self-destructing object ("X-ing out" of the form would otherwise destroy the instance).</li>
</ul>
<p>In this case the code-behind might look like this:</p>
<pre><code>Option Explicit
Private Type TView
Model As FilterModel
IsCancelled As Boolean
End Type
Private this As TView
Public Property Get Model() As FilterModel
Set Model = this.Model
End Property
Public Property Set Model(ByVal value As FilterModel)
Set this.Model = value
Validate
End Property
Public Property Get IsCancelled() As Boolean
IsCancelled = this.IsCancelled
End Property
Private Sub TextBox1_Change()
this.Model.SelectedFilter = TextBox1.Text
Validate
End Sub
Private Sub OkButton_Click()
Me.Hide
End Sub
Private Sub Validate()
OkButton.Enabled = this.Model.IsValid
End Sub
Private Sub CancelButton_Click()
OnCancel
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = VbQueryClose.vbFormControlMenu Then
Cancel = True
OnCancel
End If
End Sub
Private Sub OnCancel()
this.IsCancelled = True
Me.Hide
End Sub
</code></pre>
<p>That's literally all the form does. <strong>It isn't responsible for knowing where the data comes from or what to do with it</strong>.</p>
<hr>
<h3>The Presenter</h3>
<p>That's the "glue" object that connects the dots.</p>
<pre><code>Option Explicit
Public Sub DoSomething()
Dim m As FilterModel
Set m = New FilterModel
With New FilterForm
Set .Model = m 'set the model
.Show 'display the dialog
If Not .IsCancelled Then 'how was it closed?
'consume the data
Debug.Print m.SelectedFilter
End If
End With
End Sub
</code></pre>
<p>If the data in the model needed to come from a database, or some worksheet, it uses a class instance (yes, <em>another</em> object!) that's responsible for doing just that.</p>
<p>The calling code could be your ActiveX button's click handler, <code>New</code>-ing up the presenter and calling its <code>DoSomething</code> method.</p>
<hr>
<p>This isn't everything there is to know about OOP in VBA (I didn't even mention interfaces, polymorphism, test stubs and unit testing), but if you want objectively scalable code, you'll want to go down the MVP rabbit hole and explore the possibilities truly object-oriented code bring to VBA.</p>
<hr>
<h3>TL;DR:</h3>
<p>Code ("business logic") simply doesn't <em>belong</em> in forms' code-behind, in any code base that means to scale and be maintained across several years.</p>
<p>In "variant 1" the code is hard to follow because you're jumping between modules and the presentation concerns are mixed with the application logic: it's not the form's job to know what other form to show given button A or button B was pressed. Instead it should let the <em>presenter</em> know what the user means to do, and act accordingly.</p>
<p>In "variant 2" the code is hard to follow because everything is hidden in userforms' code-behind: we don't know what the application logic is unless we dig into that code, which now <em>purposely</em> mixes presentation and business logic concerns. That is <em>exactly</em> what the "Smart UI" anti-pattern does.</p>
<p>In other words variant 1 is slightly better than variant 2, because at least the logic isn't in the code-behind, but it's still a "Smart UI" because it's <em>running the show</em> instead of <em>telling its caller what's happening</em>.</p>
<p>In both cases, coding against the forms' default instances is harmful, because it puts state in global scope (anyone can access the default instances and do anything to its state, from anywhere in the code).</p>
<p>Treat forms like the objects they are: instantiate them!</p>
<p>In both cases, because the form's code is tightly coupled with the application logic and intertwined with presentation concerns, it's completely impossible to write a single unit test that covers even one single aspect of what's going on. With the MVP pattern, you can completely decouple the components, abstract them behind interfaces, isolate responsibilities, and write dozens of automated unit tests that cover every single piece of functionality and document exactly what the specifications are - without writing a single bit of documentation: <em>the code becomes its own documentation</em>.</p> |
33,318,499 | Should I use quotes in environment path names? | <p>I'm in the process of cleaning up all my config files in an attempt to make them as readable as possible. I've been looking for a style guide on the use of quotes while exporting paths in, for example, a <code>~/.bashrc</code> file:</p>
<pre><code>export PATH="/users/me/path:$PATH"
</code></pre>
<p>vs</p>
<pre><code>export PATH=/users/me/path:$PATH
</code></pre>
<p>The Google <a href="https://google.github.io/styleguide/shellguide.html#s5.7-quoting" rel="noreferrer">shell style</a> guide suggests avoiding quotes for path names. In contrast, a lot of the popular dotfiles repos (such as Zach Holman's <a href="https://github.com/holman/dotfiles/blob/75183cecb9d7c7c4a7cf5e9301cefffd2abf8ef7/system/_path.zsh" rel="noreferrer">here</a>) use quotes. Are there any situations when it is an advantage to use quotes in the path?</p> | 33,318,886 | 3 | 3 | null | 2015-10-24 13:00:06.903 UTC | 19 | 2021-09-17 14:31:48.207 UTC | 2021-09-17 14:31:48.207 UTC | null | 9,418,981 | null | 2,436,744 | null | 1 | 53 | bash|shell|dotfiles | 32,408 | <p><sup>Tip of the hat to <a href="https://stackoverflow.com/users/1815797/gniourf-gniourf">@gniourf_gniourf</a> and <a href="https://stackoverflow.com/users/1126841/chepner">@chepner</a> for their help.</sup></p>
<p><strong>tl;dr</strong></p>
<p><strong>To be safe, double-quote: it'll work in all cases, across all POSIX-like shells.</strong></p>
<p>If you want to add a <code>~</code>-based path, <em>selectively</em> leave the <code>~/</code> <em>unquoted</em> to ensure that <code>~</code> is expanded; e.g.: <code>export PATH=~/"bin:$PATH"</code>.
<sup>See below for the rules of <code>~</code> expansion in variable assignments.</sup><br>
Alternatively, simply use <code>$HOME</code> inside a single, double-quoted string:<br>
<code>export PATH="$HOME/bin:$PATH"</code></p>
<hr>
<p>NOTE: The following applies to <strong><code>bash</code>, <code>ksh</code>, and <code>zsh</code></strong>, but NOT to (mostly) strictly POSIX compliant shells such as <code>dash</code>; thus, <strong>when you target <code>/bin/sh</code>, you MUST double-quote the RHS of <code>export</code></strong>.<sup>[1]</sup></p>
<ul>
<li>Double-quotes are <strong><em>optional</em>, ONLY IF the <em>literal</em> part of your RHS (the value to assign) contains neither whitespace nor other shell metacharacters.</strong></li>
<li>Whether the values of the <em>variables referenced</em> contain whitespace/metacharacters or not does <em>not</em> matter - see below.
<ul>
<li>Again: It <em>does</em> matter with <code>sh</code>, when <code>export</code> is used, so always double-quote there.</li>
</ul></li>
</ul>
<p>The reason you can get away without double-quoting in this case is that <strong><em>variable-assignment</em> statements in POSIX-like shells interpret their RHS <em>differently</em> than <em>arguments</em> passed to <em>commands</em></strong>, as described in <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_01" rel="noreferrer">section 2.9.1</a> of the POSIX spec:</p>
<ul>
<li><p>Specifically, even though <em>initial</em> word-splitting <em>is</em> performed, it is only applied to the <em>unexpanded</em> (raw) RHS (that's why you <em>do</em> need quoting with whitespace/metacharacters in <em>literals</em>), and not to its <em>results</em>.</p></li>
<li><p>This <strong>only applies to <em>genuine</em> assignment statements of the form<br>
<code><name>=<value></code> in <em>all</em> POSIX-like shells</strong>, i.e., if there is <em>no command name</em> before the variable name; note that that includes assignments <em>prepended</em> to a command to define ad-hoc environment variables for it, e.g., <code>foo=$bar cmd ...</code>.</p></li>
<li><p><strong>Assignments <em>in the context of other commands</em> should always be double-quoted</strong>, to be safe:</p>
<ul>
<li><p>With <code>sh</code> (in a (mostly) strictly POSIX-compliant shell such as <code>dash</code>) an assignment with <code>export</code> is treated as a <em>regular command</em>, and the <code>foo=$bar</code> part is treated as the <em>1st argument</em> to the <code>export</code> builtin and therefore treated as usual (subject to word-splitting of the <em>result</em>, too).<br>
(POSIX doesn't specify any other commands involving (explicit) variable-assignment; <code>declare</code>, <code>typeset</code>, and <code>local</code> are nonstandard <em>extensions</em>).</p></li>
<li><p><code>bash</code>, <code>ksh</code>, <code>zsh</code>, in an understandable deviation from POSIX, extend the assignment logic to <code>export foo=$bar</code> and <code>typeset/declare/local foo=$bar</code> as well. In other words: <strong>in <code>bash</code>, <code>ksh</code>, <code>zsh</code>, <code>export/typeset/declare/local</code> commands are treated like <em>assignments</em>, so that quoting isn't strictly necessary</strong>.</p>
<ul>
<li>Perhaps surprisingly, <code>dash</code>, which also chose to implement the <em>non</em>-POSIX <code>local</code> builtin<sup>[2]</sup>
, does NOT extend assignment logic to it; it is consistent with its <code>export</code> behavior, however.</li>
</ul></li>
<li><p>Assignments passed to <code>env</code> (e.g., <code>env foo=$bar cmd ...</code>) are also subject to expansion as a command argument and therefore need double-quoting - except in <code>zsh</code>.</p>
<ul>
<li>That <code>env</code> acts differently from <code>export</code> in <code>ksh</code> and <code>bash</code> in that regard is due to the fact that <code>env</code> is an <em>external utility</em>, whereas <code>export</code> is a <em>shell builtin</em>.<br>
(<code>zsh</code>'s behavior <em>fundamentally</em> differs from that of the other shells when it comes to unquoted variable references).</li>
</ul></li>
</ul></li>
<li><p><strong>Tilde (<code>~</code>) expansion happens as follows in <em>genuine</em> assignment statements</strong>:</p>
<ul>
<li>In addition to the <code>~</code> needing to be <em>unquoted</em>, as usual, it is also only applied:
<ul>
<li>If the <em>entire</em> RHS is <code>~</code>; e.g.:
<ul>
<li><code>foo=~ # same as: foo="$HOME"</code></li>
</ul></li>
<li>Otherwise: <em>only</em> if <em>both</em> of the following conditions are met:
<ul>
<li>if <code>~</code> starts the string or is preceded by an <em>unquoted</em> <code>:</code></li>
<li>if <code>~</code> is followed by an <em>unquoted</em> <code>/</code>.</li>
<li>e.g.,<br>
<code>foo=~/bin # same as foo="$HOME/bin"</code><br>
<code>foo=$foo:~/bin # same as foo="$foo:$HOME/bin"</code></li>
</ul></li>
</ul></li>
</ul></li>
</ul>
<p><strong>Example</strong></p>
<p>This example demonstrates that in <code>bash</code>, <code>ksh</code>, and <code>zsh</code> you can get away <em>without</em> double-quoting, even when using <code>export</code>, but <em>I do not recommend it</em>.</p>
<pre><code>#!/usr/bin/env bash
# or ksh or zsh - but NOT /bin/sh!
# Create env. variable with whitespace and other shell metacharacters
export FOO="b:c &|<> d"
# Extend the value - the double quotes here are optional, but ONLY
# because the literal part, 'a:`, contains no whitespace or other shell metacharacters.
# To be safe, DO double-quote the RHS.
export FOO=a:$foo # OK - $FOO now contains 'a:b:c &|<> d'
</code></pre>
<hr>
<p><sup>[1] As @gniourf_gniourf points out: Use of <code>export</code> to <em>modify</em> the value of <code>PATH</code> is optional, because once a variable is marked as exported, you can use a regular assignment (<code>PATH=...</code>) to change its value.<br>
That said, you may still <em>choose</em> to use <code>export</code>, so as to make it explicit that the variable being modified is exported.</sup></p>
<p><sup>[2] @gniourf_gniourf states that a future version of the POSIX standard may introduce the <code>local</code> builtin.</sup></p> |
1,767,946 | GetThreadLocale returns different value than GetUserDefaultLCID? | <p>To get the locale settings, e.g. short date format, we've always used GetLocaleFormatSettings with GetThreadLocale. This has always worked without problem until now.</p>
<p>A couple of our users are getting different values for GetThreadLocale that don't match what they've configured in the regional settings in Windows 7. We've been unable to reproduce this no matter what we try, but I sent one user a test program to get the locale information, and sure enough GetThreadLocale returns a different LCID (1033) than GetUserDefaultLCID (2057). So instead of getting UK locale settings, they end up with US locale settings.</p>
<p>Are we getting the locale information incorrectly? Should we be using GetUserDefaultLCID instead of GetThreadLocale?</p>
<p>Thanks</p> | 1,768,880 | 5 | 1 | null | 2009-11-20 02:26:49.307 UTC | 11 | 2011-12-01 13:45:20.89 UTC | null | null | null | null | 214,307 | null | 1 | 18 | delphi|windows-7 | 15,911 | <p>You're not the only one. I've seen this too with Windows 7 here in New Zealand and it seems to only trip up Delphi applications for some reason as far as I can tell.</p>
<p>The strange thing we found is that switching to a different regional settings via Control Panel and then switching back to NZ resolves the issue. I'd be curious to know if the same workaround resolves it for you just to verify that we're seeing the same phenomenon.</p>
<p>I'm wondering if selecting non-US regional settings via the Windows 7 install process is not quite 'doing the right thing' in some subtle way that only trips up Delphi applications for some reason.</p>
<p>I'd arrived at similar test code to JP's in an attempt to track it down and find a software workaround but our QA guy had since found the 'regional settings switcheroo' workaround and he didn't fancy completely reinstalling Windows 7 again to get back to the original funky state for some reason :-)</p> |
2,228,544 | higher level functions in R - is there an official compose operator or curry function? | <p>I can create a compose operator in R:</p>
<pre><code> `%c%` = function(x,y)function(...)x(y(...))
</code></pre>
<p>To be used like this:</p>
<pre><code> > numericNull = is.null %c% numeric
> numericNull(myVec)
[2] TRUE FALSE
</code></pre>
<p>but I would like to know if there is an official set of functions to do this kind of thing and other operations such as currying in R. Largely this is to reduce the number of brackets, function keywords etc in my code.</p>
<p>My curry function:</p>
<pre><code>> curry=function(...){
z1=z0=substitute(...);z1[1]=call("list");
function(...){do.call(as.character(z0[[1]]),
as.list(c(eval(z1),list(...))))}}
> p = curry(paste(collapse=""))
> p(letters[1:10])
[1] "abcdefghij"
</code></pre>
<p>This is especially nice for e.g. aggregate:</p>
<pre><code>> df = data.frame(l=sample(1:3,10,rep=TRUE), t=letters[1:10])
> aggregate(df$t,df["l"],curry(paste(collapse="")) %c% toupper)
l x
1 1 ADG
2 2 BCH
3 3 EFIJ
</code></pre>
<p>Which I find much more elegant and editable than:</p>
<pre><code>> aggregate(df$t, df["l"], function(x)paste(collapse="",toupper(x)))
l x
1 1 ADG
2 2 BCH
3 3 EFIJ
</code></pre>
<p>Basically I want to know - has this already been done for R?</p> | 32,865,781 | 5 | 5 | null | 2010-02-09 11:10:44.32 UTC | 26 | 2022-05-25 02:31:55.69 UTC | 2010-02-09 14:16:23.603 UTC | null | 7,851 | null | 121,332 | null | 1 | 38 | r|functional-programming|higher-order-functions | 6,355 | <p>The standard place for functional programming in R is now the <code>functional</code> library. </p>
<p>From the library:</p>
<blockquote>
<p>functional: Curry, Compose, and other higher-order functions</p>
</blockquote>
<p>Example:</p>
<pre><code> library(functional)
newfunc <- Curry(oldfunc,x=5)
</code></pre>
<p>CRAN:
<a href="https://cran.r-project.org/web/packages/functional/index.html" rel="noreferrer">https://cran.r-project.org/web/packages/functional/index.html</a></p>
<p>PS: This library substitutes the <code>ROxigen</code> library.</p> |
1,547,381 | How do I cache a web page in PHP? | <p>how do I cache a web page in php so that if a page has not been updated viewers should get a cached copy? </p>
<p>Thanks for your help.
PS: I am beginner in php.</p> | 1,547,394 | 6 | 3 | null | 2009-10-10 08:22:39.053 UTC | 10 | 2022-09-13 16:35:16.317 UTC | null | null | null | null | 187,580 | null | 1 | 16 | php|caching | 13,461 | <p>You can actually save the output of the page before you end the script, then load the cache at the start of the script.</p>
<p>example code:</p>
<pre><code><?php
$cachefile = 'cache/'.basename($_SERVER['PHP_SELF']).'.cache'; // e.g. cache/index.php.cache
$cachetime = 3600; // time to cache in seconds
if (file_exists($cachefile) && time() - $cachetime <= filemtime($cachefile)) {
$c = @file_get_contents($cachefile);
echo $c;
exit;
} else {
unlink($cachefile);
}
ob_start();
// all the coding goes here
$c = ob_get_contents();
file_put_contents($cachefile, $c);
?>
</code></pre>
<p>If you have a lot of pages needing this caching you can do this:</p>
<p>in <code>cachestart.php</code>:</p>
<pre><code><?php
$cachefile = 'cache/' . basename($_SERVER['PHP_SELF']) . '.cache'; // e.g. cache/index.php.cache
$cachetime = 3600; // time to cache in seconds
if (file_exists($cachefile) && time() - $cachetime <= filemtime($cachefile)) {
$c = @file_get_contents($cachefile);
echo $c;
exit;
} else {
unlink($cachefile);
}
ob_start();
?>
</code></pre>
<p>in <code>cacheend.php</code>:</p>
<pre><code><?php
$c = ob_get_contents();
file_put_contents($cachefile, $c);
?>
</code></pre>
<p>Then just simply add</p>
<pre><code>include('cachestart.php');
</code></pre>
<p>at the start of your scripts. and add</p>
<pre><code>include('cacheend.php');
</code></pre>
<p>at the end of your scripts. Remember to have a folder named <em>cache</em> and allow PHP to access it.</p>
<p>Also do remember that if you're doing a full page cache, your page should not have SESSION specific display (e.g. display members' bar or what) because they will be cached as well. Look at a framework for specific-caching (variable or part of the page).</p> |
1,402,566 | What is the difference between ' and " in PHP? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/1318028/php-different-quotes">PHP: different quotes?</a> </p>
</blockquote>
<p>Simple question:</p>
<p>What is the difference between ' and " in php? When should I use either?</p> | 1,402,580 | 6 | 5 | null | 2009-09-09 22:54:14.457 UTC | 8 | 2012-08-31 11:45:55.467 UTC | 2017-05-23 12:18:27.56 UTC | null | -1 | null | 54,408 | null | 1 | 29 | php|syntax | 53,794 | <p>Basically, single-quoted strings are plain text with virtually no special case whereas double-quoted strings have variable interpolation (e.g. <code>echo "Hello $username";</code>) as well as escaped sequences such as "\n" (newline.)</p>
<p>You can learn more about strings in <a href="http://docs.php.net/manual/en/language.types.string.php" rel="noreferrer">PHP's manual</a>.</p> |
1,929,038 | Compilation error - ICE80: The 64BitComponent ... uses 32BitDirectory | <p>The following line</p>
<pre><code><Component Guid='{THE_GUID}' Id='GlobalScopePackages' >
</code></pre>
<p>Generates the following error:</p>
<pre><code>Error 4 ICE80: This 64BitComponent GlobalScopePackages uses 32BitDirectory blablabla c:\development\...\file.wxs
</code></pre>
<p>Error is described on this page
<a href="http://msdn.microsoft.com/en-us/library/aa369034(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa369034(VS.85).aspx</a></p>
<p>How do I fix this or suppress the warning? Is it safe to simply supress the warning?</p> | 4,642,991 | 6 | 0 | null | 2009-12-18 15:58:24.083 UTC | 7 | 2019-05-02 08:23:20.56 UTC | 2013-01-07 16:38:51.917 UTC | null | 1,551 | null | 1,551 | null | 1 | 29 | c#|.net|compiler-construction | 19,113 | <p>You can also set <code>Win64="no"</code> in the <code><Component /></code> tag of the components which are not 64-bit.</p>
<p>But I can confirm you can ignore this.</p> |
2,218,118 | What is the difference between graph-based databases and object-oriented databases? | <p>What is the difference between graph-based databases (<a href="http://neo4j.org/" rel="noreferrer">http://neo4j.org/</a>) and object-oriented databases (<a href="http://www.db4o.com/" rel="noreferrer">http://www.db4o.com/</a>)?</p> | 2,233,665 | 6 | 0 | null | 2010-02-07 20:04:16.467 UTC | 27 | 2011-08-24 20:31:19.847 UTC | 2011-08-24 20:31:19.847 UTC | null | 852,604 | null | 14,731 | null | 1 | 52 | database|db4o|neo4j|graph-databases|object-oriented-database | 11,935 | <p>I'd answer this differently: object and graph databases operate on two different levels of abstraction.</p>
<p>An object database's main data elements are objects, the way we know them from an object-oriented programming language. </p>
<p>A graph database's main data elements are nodes and edges.</p>
<p>An object database does not have the notion of a (bidirectional) edge between two things with automatic referential integrity etc. A graph database does not have the notion of a pointer that can be NULL. (Of course one can imagine hybrids.)</p>
<p>In terms of schema, an object database's schema is whatever the set of classes is in the application. A graph database's schema (whether implicit, by convention of what String labels mean, or explicit, by declaration as models as we do it in <a href="http://infogrid.org/" rel="noreferrer">InfoGrid</a> for example) is independent of the application. This makes it much simpler, for example, to write multiple applications against the same data using a graph database instead of an object database, because the schema is application-independent. On the other hand, using a graph database you can't simply take an arbitrary object and persist it.</p>
<p>Different tools for different jobs I would think.</p> |
2,079,448 | Positioning jQuery dialog | <p>I want to position my jQuery dialog x-pixels away from the right border of the browser. Is this anyhow possible?</p>
<p><a href="http://jqueryui.com/demos/dialog/" rel="noreferrer">http://jqueryui.com/demos/dialog/</a></p>
<p>The position option doesn't seem to have that kind of setup, but is there any other way to do it?</p> | 2,079,468 | 8 | 1 | null | 2010-01-16 23:59:31.543 UTC | 4 | 2020-05-10 21:06:19.187 UTC | null | null | null | null | 251,981 | null | 1 | 15 | jquery|dialog|css-position | 38,081 | <p>If you make your dialog box's <code>position:absolute</code>, then its taken about of the regular page flow, and you can use the <code>left</code> and <code>top</code> property to place it anywhere on the page.</p>
<pre><code>$('.selector').dialog({ dialogClass: 'myPosition' });
</code></pre>
<p>and define the myPosition css class as:</p>
<pre><code>.myPosition {
position: absolute;
right: 200px; /* use a length or percentage */
}
</code></pre>
<p>You can set the <code>top</code>, <code>left</code>, <code>right</code>, and <code>bottom</code> <a href="http://www.w3schools.com/Css/pr_pos_left.asp" rel="noreferrer">properties</a> for <code>myPosition</code> using either a length such as in pixels or percentage.</p> |
1,783,912 | How to use BigInteger? | <p>I have this piece of code, which is not working:</p>
<pre><code>BigInteger sum = BigInteger.valueOf(0);
for(int i = 2; i < 5000; i++) {
if (isPrim(i)) {
sum.add(BigInteger.valueOf(i));
}
}
</code></pre>
<p>The sum variable is always 0. What am I doing wrong?</p> | 1,783,929 | 10 | 3 | null | 2009-11-23 15:37:11.353 UTC | 39 | 2022-06-18 12:04:39.73 UTC | 2018-08-28 09:36:50.813 UTC | null | 479,156 | null | 183,270 | null | 1 | 154 | java|biginteger | 342,427 | <p><code>BigInteger</code> is immutable. The javadocs states that <a href="https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#add-java.math.BigInteger-" rel="noreferrer"><strong>add()</strong></a> "[r]eturns a BigInteger whose value is (this + val)." Therefore, you can't change <code>sum</code>, you need to reassign the result of the <code>add</code> method to <code>sum</code> variable.</p>
<pre><code>sum = sum.add(BigInteger.valueOf(i));
</code></pre> |
1,408,356 | Keyboard Interrupts with python's multiprocessing Pool | <p>How can I handle KeyboardInterrupt events with python's multiprocessing Pools? Here is a simple example:</p>
<pre><code>from multiprocessing import Pool
from time import sleep
from sys import exit
def slowly_square(i):
sleep(1)
return i*i
def go():
pool = Pool(8)
try:
results = pool.map(slowly_square, range(40))
except KeyboardInterrupt:
# **** THIS PART NEVER EXECUTES. ****
pool.terminate()
print "You cancelled the program!"
sys.exit(1)
print "\nFinally, here are the results: ", results
if __name__ == "__main__":
go()
</code></pre>
<p>When running the code above, the <code>KeyboardInterrupt</code> gets raised when I press <code>^C</code>, but the process simply hangs at that point and I have to kill it externally.</p>
<p>I want to be able to press <code>^C</code> at any time and cause all of the processes to exit gracefully.</p> | 1,408,476 | 11 | 1 | null | 2009-09-10 23:59:35.597 UTC | 52 | 2022-06-10 12:41:27.707 UTC | null | null | null | null | 121,112 | null | 1 | 156 | python|multiprocessing|pool|keyboardinterrupt | 89,979 | <p>This is a Python bug. When waiting for a condition in threading.Condition.wait(), KeyboardInterrupt is never sent. Repro:</p>
<pre><code>import threading
cond = threading.Condition(threading.Lock())
cond.acquire()
cond.wait(None)
print "done"
</code></pre>
<p>The KeyboardInterrupt exception won't be delivered until wait() returns, and it never returns, so the interrupt never happens. KeyboardInterrupt should almost certainly interrupt a condition wait.</p>
<p>Note that this doesn't happen if a timeout is specified; cond.wait(1) will receive the interrupt immediately. So, a workaround is to specify a timeout. To do that, replace</p>
<pre><code> results = pool.map(slowly_square, range(40))
</code></pre>
<p>with</p>
<pre><code> results = pool.map_async(slowly_square, range(40)).get(9999999)
</code></pre>
<p>or similar.</p> |
1,539,793 | In Java does anyone use short or byte? | <p>Apart from using (byte[]) in streaming I don't really see byte and short used much. On the other hand I have seen long used where the actual value is |100| and byte would be more appropriate. Is this a consequence of the relative inexpensive nature of memory now or is this just minutia that developers needn't worry about? </p> | 1,539,814 | 12 | 0 | null | 2009-10-08 19:00:09.14 UTC | 8 | 2021-07-25 19:51:38.9 UTC | 2018-11-09 18:16:32.997 UTC | null | 397,817 | null | 117,783 | null | 1 | 43 | java | 14,429 | <p>They are used when programming for embedded devices that are short on memory or disk space. Such as appliances and other electronic devices.</p>
<p>Byte is also used in low level web programming, where you send requests to web servers using headers, etc.</p> |
2,077,550 | How can I enable auto-updates in a Qt cross-platform application? | <p>I love applications that are able to update themselves without any effort from the user (think: <a href="http://en.wikipedia.org/wiki/Sparkle_%28software%29" rel="noreferrer">Sparkle</a> framework for Mac). Is there any code/library I can leverage to do this in a Qt application, without having to worry about the OS details? </p>
<p>At least for Windows, Mac and user-owned Linux binaries.</p>
<p>I could integrate Sparkle on the Mac version, code something for the Linux case (only for a standalone, user-owned binary; I won't mess with <a href="http://en.wikipedia.org/wiki/Linux_distribution" rel="noreferrer">distribution</a> packaging, if my program is ever packaged), and find someone to help me on the Windows side, but that's horribly painful. </p> | 2,127,464 | 13 | 0 | null | 2010-01-16 14:11:00.63 UTC | 30 | 2021-04-28 11:08:16.77 UTC | 2013-05-11 13:12:52.787 UTC | null | 63,550 | null | 143,495 | null | 1 | 49 | qt|cross-platform|auto-update | 22,804 | <p>OK, so I guess I take it as a "no (cross-platform) way". It's too bad!</p> |
2,326,943 | When do items in HTML5 local storage expire? | <p>For how long is data stored in <code>localStorage</code> (as part of DOM Storage in HTML5) available? Can I set an expiration time for the data which I put into local storage?</p> | 2,327,030 | 18 | 1 | null | 2010-02-24 15:02:36.513 UTC | 95 | 2022-08-09 04:25:45.53 UTC | 2020-07-01 15:41:06.717 UTC | null | 362,780 | null | 280,427 | null | 1 | 408 | javascript|html|local-storage | 366,216 | <p>It's not possible to specify expiration. It's completely up to the user.</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage</a></p>
<p>Of course, it's possible that something your application stores on the client may not be there later. The user can explicitly get rid of local storage, or the browser may run into space considerations. It's good to program defensively. Generally however things remain "forever" based on some practical definition of that word.</p>
<p><em>edit</em> — obviously, your own application can actively remove stuff if it decides it's too old. That is, you can explicitly include some sort of timestamp in what you've got saved, and then use that later to decide whether or not information should be flushed.</p> |
8,559,217 | Python - Update a value in a list of tuples | <p>What is the best way to update a value in a list of tuples?</p>
<p>I currently do it like in the code below, but I suppose there is a cleaner and concise way.</p>
<pre><code>>>> foo = [('a', 'hello'), ('b', 'world')]
>>> bar = dict(foo)
>>> bar['b'] = 'friend'
>>> foo = bar.items()
>>> foo
[('a', 'hello'), ('b', 'friend')]
</code></pre>
<p>Edit: The reason to use a list of tuple wasn't clear in my original post.
The goal is to update some headers values of a wsgi application during error handling, that are a list of tuples.</p>
<p>Thanks in advance.</p> | 8,559,379 | 4 | 2 | null | 2011-12-19 09:20:15.623 UTC | 4 | 2013-03-11 06:04:20.66 UTC | 2011-12-19 09:55:15.15 UTC | null | 1,076,715 | null | 1,076,715 | null | 1 | 15 | python | 38,303 | <p>Your data structure (a list of tuple) is best referred as an associative list. As other pointed out, it is probably better to use a dictionary as you'll get better amortized cost on operation (insertion, deletion, and lookup are O(1) for a dictionary, but deletion and lookup are O(n) for associative list).</p>
<p>Concerning updating your associative list by converting it to a dictionary, and then back to an associative list, this method has three drawbacks. It is quite expensive, it may change the order of the items, and it will remove duplicate.</p>
<p>If you want to keep using associative lists, it is probably better to just use a list comprehension to update the data structure. The cost will be O(n) in time and memory, but that's already what you have when using an intermediate dictionary.</p>
<p>Here's a simple way to do it (require Python 2.5 because it use the ternary operator):</p>
<pre><code>def update_in_alist(alist, key, value):
return [(k,v) if (k != key) else (key, value) for (k, v) in alist]
def update_in_alist_inplace(alist, key, value):
alist[:] = update_in_alist(alist, key, value)
>>> update_in_alist([('a', 'hello'), ('b', 'world')], 'b', 'friend')
[('a', 'hello'), ('b', 'friend')]
</code></pre> |
17,965,956 | How to get element by class name? | <p>Using JavaScript, we can get element by id using following syntax:</p>
<pre><code>var x=document.getElementById("by_id");
</code></pre>
<p>I tried following to get element by class:</p>
<pre><code>var y=document.getElementByClass("by_class");
</code></pre>
<p>But it resulted into error: </p>
<pre><code>getElementByClass is not function
</code></pre>
<p>How can I get an element by its class?</p> | 17,965,968 | 4 | 2 | null | 2013-07-31 09:00:58.913 UTC | 42 | 2020-03-31 05:02:05.167 UTC | 2013-07-31 09:04:22.287 UTC | null | 20,578 | null | 1,471,417 | null | 1 | 188 | javascript|dom | 574,069 | <p>The name of the DOM function is actually <code>getElementsByClassName</code>, not <code>getElementByClassName</code>, simply because more than one element on the page can have the same class, hence: <code>Elements</code>.</p>
<p>The return value of this will be a NodeList instance, or a superset of the <code>NodeList</code> (FF, for instance returns an instance of <code>HTMLCollection</code>). At any rate: the return value is an array-like object:</p>
<pre><code>var y = document.getElementsByClassName('foo');
var aNode = y[0];
</code></pre>
<p>If, for some reason you <em>need</em> the return object as an array, you can do that easily, because of its magic length property:</p>
<pre><code>var arrFromList = Array.prototype.slice.call(y);
//or as per AntonB's comment:
var arrFromList = [].slice.call(y);
</code></pre>
<p>As <a href="https://stackoverflow.com/a/17966004/5411817">yckart</a> suggested <code>querySelector('.foo')</code> and <code>querySelectorAll('.foo')</code> would be preferable, though, as they are, indeed, better supported (93.99% vs 87.24%), according to caniuse.com:</p>
<ul>
<li><a href="http://caniuse.com/queryselector" rel="noreferrer">querySelector(all)</a></li>
<li><a href="http://caniuse.com/getelementsbyclassname" rel="noreferrer">getElementsByClassName</a></li>
<li><a href="http://www.w3fools.com" rel="noreferrer">Don't use w3schools to learn something</a></li>
<li><a href="https://developer.mozilla.org/en-US/" rel="noreferrer">Refer to MDN for accurate information</a></li>
</ul> |
6,361,428 | How can I send sms messages in the BACKGROUND using Android? | <p>I am coming from iphone development where you cannot send an SMS in the background without asking the user to confirm the send. Can sms be sent in the background in android so that no user intervention is need?</p> | 13,491,005 | 4 | 1 | null | 2011-06-15 17:00:45.35 UTC | 10 | 2020-08-05 17:16:55.54 UTC | 2014-02-26 07:22:41.017 UTC | null | 3,283,322 | null | 190,822 | null | 1 | 15 | android|sms|smsmanager | 24,559 | <p>Send SMS with SMS-Delivery notification as toast.</p>
<p>method call as below.</p>
<pre><code>sendSMS("98********","This is test message");
</code></pre>
<p>method signature as below.</p>
<pre><code>/*
* BroadcastReceiver mBrSend; BroadcastReceiver mBrReceive;
*/
private void sendSMS(String phoneNumber, String message) {
ArrayList<PendingIntent> sentPendingIntents = new ArrayList<PendingIntent>();
ArrayList<PendingIntent> deliveredPendingIntents = new ArrayList<PendingIntent>();
PendingIntent sentPI = PendingIntent.getBroadcast(mContext, 0,
new Intent(mContext, SmsSentReceiver.class), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(mContext, 0,
new Intent(mContext, SmsDeliveredReceiver.class), 0);
try {
SmsManager sms = SmsManager.getDefault();
ArrayList<String> mSMSMessage = sms.divideMessage(message);
for (int i = 0; i < mSMSMessage.size(); i++) {
sentPendingIntents.add(i, sentPI);
deliveredPendingIntents.add(i, deliveredPI);
}
sms.sendMultipartTextMessage(phoneNumber, null, mSMSMessage,
sentPendingIntents, deliveredPendingIntents);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "SMS sending failed...",Toast.LENGTH_SHORT).show();
}
}
</code></pre>
<p>Now two more classes SmsDeliveredReceiver,SmsSentReceiver as below.</p>
<pre><code>public class SmsDeliveredReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(context, "SMS delivered", Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(context, "SMS not delivered", Toast.LENGTH_SHORT).show();
break;
}
}
}
</code></pre>
<p>Now SmsSentReceiver.</p>
<pre><code>public class SmsSentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(context, "SMS Sent", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(context, "SMS generic failure", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(context, "SMS no service", Toast.LENGTH_SHORT)
.show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(context, "SMS null PDU", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(context, "SMS radio off", Toast.LENGTH_SHORT).show();
break;
}
}
}
</code></pre>
<p>Now Permissions open your AndroidManifest.xml and add below line</p>
<pre><code><uses-permission android:name="android.permission.SEND_SMS"/>
</code></pre>
<p>and its done.......</p> |
23,731,309 | Fragment without activity | <p>I have been asked an interview question: <strong>Can a fragment exist without activity</strong>? I searched for answers but didn't get a proper answer and explanation. Can someone help?</p> | 23,731,497 | 7 | 2 | null | 2014-05-19 06:48:01.95 UTC | 8 | 2018-12-21 03:25:46.693 UTC | 2018-12-21 03:25:46.693 UTC | null | 1,402,846 | null | 2,297,882 | null | 1 | 27 | android|android-fragments | 10,919 | <p>Yes, you can do this anywhere:</p>
<pre><code>new YourFragment();
</code></pre>
<p>As fragments must have a parameter-less constructor.</p>
<p>However its <a href="http://developer.android.com/guide/components/fragments.html">lifecycle</a> doesn't kick in until it is attached. So <code>onAttach</code>, <code>onCreate</code>, <code>onCreateView</code>, etc. are only called when it is attached. So most fragments do nothing until they are attached.</p> |
15,598,757 | oracle.jdbc.driver.OracleDriver ClassNotFoundException | <p>This is my code for which I am getting error. My <code>classes12.jar</code> has been imported as an external jar.</p>
<pre><code>import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginAction extends HttpServlet {
Connection conn;
Statement stmt;
ResultSet rs;
String query = "SELECT * FROM v_urja_login";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello");
String u_name = request.getParameter("uname");
String u_pass = request.getParameter("upass");
out.println(u_name);
out.println(u_pass);
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","urja","urja");
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
}catch(SQLException sex){
sex.printStackTrace();
} catch (ClassNotFoundException cnf) {
cnf.printStackTrace();
}
}
}
</code></pre>
<p>Stacktrace:</p>
<pre><code>java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at LoginAction.doPost(LoginAction.java:27)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:931)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
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)
</code></pre> | 15,598,892 | 8 | 3 | null | 2013-03-24 12:59:51.047 UTC | 3 | 2019-12-18 12:33:20.1 UTC | 2013-03-25 04:16:56.7 UTC | null | 559,026 | null | 2,194,480 | null | 1 | 10 | java|eclipse|jdbc|oracle10g|classnotfoundexception | 149,981 | <pre><code> Class.forName("oracle.jdbc.driver.OracleDriver");
</code></pre>
<p>This line causes <code>ClassNotFoundException</code>, because you haven't placed <code>ojdbc14.jar</code> file in your lib folder of the project. or YOu haven't set the <code>classpath</code> of the required jar</p> |
40,164,169 | CSS Variables (custom properties) in Pseudo-element "content" Property | <p>Example use (what I want)</p>
<pre><code>div::after {
content: var(--mouse-x) ' / ' var(--mouse-y);
}
</code></pre>
<p>Test case showing it NOT working:</p>
<p><a href="http://codepen.io/jasesmith/pen/KgbdpW/?editors=0100" rel="noreferrer">CodePen: CSS Variables in Pseudo Element's "content:" Property (a test case) by Jase Smith</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-js lang-js prettyprint-override"><code>document.addEventListener('mousemove', (e) => {
document.documentElement.style.setProperty('--mouse-x', e.clientX)
document.documentElement.style.setProperty('--mouse-y', e.clientY)
// output for explanation text
document.querySelector('.x').innerHTML = e.clientX
document.querySelector('.y').innerHTML = e.clientY
})</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* what I want!! */
div::after {
content: var(--mouse-x, 245)" / " var(--mouse-y, 327);
}
/* setup and presentation styles */
div::before {
content: 'mouse position:';
}
div {
position: absolute;
top: 0;
left: 0;
transform: translate(calc(var(--mouse-x, 245) * 1px), calc(var(--mouse-y, 327) * 1px));
width: 10em;
height: 10em;
background: #ff3b80;
color: #fff;
display: flex;
flex-flow: column;
align-items: center;
justify-content: center;
border-radius: 100%;
will-change: transform;
}
body {
margin: 2em;
font-family: sans-serif;
}
p {
max-width: 50%;
min-width: 25em;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- test case: element with pseudo element -->
<div></div>
<!-- explanation (not test case) -->
<main>
<pre><code>div::after {
content: var(--mouse-x) ' / ' var(--mouse-y);
}</code></pre>
<h1>If this worked...</h1>
<p>
We should see something like this: <b><span class="x">245</span> / <span class="y">327</span></b> updating with the mousemove coordinates inside the pseudo <i>::after</i> element for the div.
</p>
</main></code></pre>
</div>
</div>
</p> | 40,179,718 | 4 | 3 | null | 2016-10-20 20:42:09.79 UTC | 12 | 2021-04-27 00:33:22.09 UTC | 2020-10-13 18:35:11.1 UTC | null | 104,380 | null | 4,172,644 | null | 1 | 43 | css|pseudo-element|css-variables | 26,058 | <p><strong>Edit for clarity:</strong> CSS custom properties with integer values can be displayed in a pseudo-element's <code>content</code> property via a <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Lists_and_Counters/Using_CSS_counters" rel="noreferrer">CSS counter</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-css lang-css prettyprint-override"><code>div {
--variable: 123;
}
span:after {
counter-reset: variable var(--variable);
content: counter(variable);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>The variable is <span></span>.</div></code></pre>
</div>
</div>
</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>.coordinates:before {
counter-reset: x var(--x) y var(--y);
content: 'The coordinates are (' counter(x) ', ' counter(y) ').';
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="coordinates" style="--x: 1; --y: 2"></div></code></pre>
</div>
</div>
</p>
<hr />
<h3>Original Answer</h3>
<p>Got it to work using a hack involving <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Lists_and_Counters/Using_CSS_counters" rel="noreferrer">CSS Counters</a>. Enjoy.</p>
<pre><code>div::after {
counter-reset: mouse-x var(--mouse-x, 245) mouse-y var(--mouse-y, 245);
content: counter(mouse-x) " / " counter(mouse-y);
}
</code></pre>
<p>Full code in action:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.addEventListener('mousemove', (e) => {
document.documentElement.style.setProperty('--mouse-x', e.clientX)
document.documentElement.style.setProperty('--mouse-y', e.clientY)
// output for explanation text
document.querySelector('.x').innerHTML = e.clientX
document.querySelector('.y').innerHTML = e.clientY
})</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* what I want!! */
div::after {
counter-reset: mouse-x var(--mouse-x, 245) mouse-y var(--mouse-y, 245);
content: counter(mouse-x) " / " counter(mouse-y);
}
/* setup and presentation styles */
div::before {
content: 'mouse position:';
}
div {
position: absolute;
top: 0;
left: 0;
transform: translate(calc(var(--mouse-x, 245) * 1px), calc(var(--mouse-y, 327) * 1px));
width: 10em;
height: 10em;
background: #ff3b80;
color: #fff;
display: flex;
flex-flow: column;
align-items: center;
justify-content: center;
border-radius: 100%;
will-change: transform;
}
body {
margin: 2em;
font-family: sans-serif;
}
p {
max-width: 50%;
min-width: 25em;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- test case: element with pseudo element -->
<div></div>
<!-- explanation (not test case) -->
<main>
<pre><code>div::after {
content: var(--mouse-x) ' / ' var(--mouse-y);
}</code></pre>
<h1>If this worked...</h1>
<p>
We should see something like this: <b><span class="x">245</span> / <span class="y">327</span></b> updating with the mousemove coordinates inside the pseudo <i>::after</i> element for the div.
</p>
</main></code></pre>
</div>
</div>
</p> |
34,389,446 | How do I download a large Git Repository? | <p>I have a GIT repository on BitBucket which is more than 4GB. </p>
<p>I can't clone the repository using the normal GIT command as it fails (looks like it's working for a long time but then rolls back).<br>
I also can't download the repository as a zip from the BitBucket interface as:</p>
<pre><code>Feature unavailable This repository is too large for us to generate a download.
</code></pre>
<p>Is there any way to download a GIT repository incrementally?</p> | 34,426,862 | 7 | 8 | null | 2015-12-21 05:26:27.433 UTC | 12 | 2020-06-03 10:44:08.12 UTC | 2017-05-16 21:25:56.643 UTC | null | 6,309 | null | 69,214 | null | 1 | 38 | git|bitbucket | 31,129 | <p>I got it to work by using this method <a href="https://stackoverflow.com/questions/21277806/fatal-early-eof-fatal-index-pack-failed/22317479#22317479">fatal: early EOF fatal: index-pack failed</a></p>
<p>But only after I setup SSL - this method still didn't work over HTTP.</p>
<p>The support at BitBucket was really helpful and pointed me in this direction.</p> |
27,657,570 | How to convert bytearray with non-ASCII bytes to string in python? | <p>I don't know how to convert Python's bitarray to string if it contains non-ASCII bytes. Example:</p>
<pre><code>>>> string='\x9f'
>>> array=bytearray(string)
>>> array
bytearray(b'\x9f')
>>> array.decode()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0x9f in position 0: ordinal not in range(128)
</code></pre>
<p>In my example, I just want to somehow get a string '\x9f' back from the bytearray. Is that possible?</p> | 27,657,615 | 4 | 2 | null | 2014-12-26 13:06:38.197 UTC | 2 | 2021-10-24 22:38:32.247 UTC | null | null | null | null | 101,152 | null | 1 | 7 | python|python-2.7 | 45,017 | <p>In Python 2, just pass it to <code>str()</code>:</p>
<pre><code>>>> import sys; sys.version_info
sys.version_info(major=2, minor=7, micro=8, releaselevel='final', serial=0)
>>> string='\x9f'
>>> array=bytearray(string)
>>> array
bytearray(b'\x9f')
>>> str(array)
'\x9f'
</code></pre>
<p>In Python 3, you'd want to convert it back to a <code>bytes</code> object:</p>
<pre><code>>>> bytes(array)
b'\x9f'
</code></pre> |
51,250,211 | Converting Object Promise to String in Javascript | <p>I'm working with React, Next.Js, semantic-ui-react and Solidity. It is my goal to print out the users address (from MetaMask) and a ProjectTitle (set by User) as meta infomation for a semantic-ui-react card. To print out the address in the 'header' is working, but I'm not able to print out the ProjectTitle as 'meta'. The Title should be a String but I'm receiving a Object Promise. </p>
<pre><code>static async getInitialProps() {
const projects = await factory.methods.getDeployedProjects().call();
return {
projects
};
}
async getProjectTitle(address) {
let title;
try {
title = await factory.methods.projectTitle(address).call();
} catch (err) {
console.log('err');
}
return title;
}
renderProjects() {
const items = this.props.projects.map(address => {
return {
header: address,
color: 'green',
description: (
<Link route={`/projects/${address}`}>
<a>View Project</a>
</Link>
),
**meta: this.getProjectTitle(address)**,
fluid: true,
style: { overflowWrap: 'break-word' }
};
}, );
return <Card.Group items={items} />
}
</code></pre>
<p>Part of the Solidity Contract:</p>
<pre><code>address[] public deployedProjects;
mapping(address => string) public projectTitle;
function createProject(string startup, string title, string deadline, string description, uint wage) public {
address newProject = new Project(startup, title, deadline, description, wage, msg.sender);
projectTitle[newProject] = title;
deployedProjects.push(newProject);
}
function getDeployedProjects() public view returns (address[]) {
return (
deployedProjects
);
}
</code></pre>
<p>The basic framework is from the Udemy Course "Ethereum and Solidity: The Complete Developer's Guide" by Stephen Grider.</p> | 51,298,188 | 1 | 3 | null | 2018-07-09 16:33:37.183 UTC | null | 2018-07-12 05:53:10.1 UTC | null | null | null | null | 10,054,782 | null | 1 | 21 | javascript|reactjs|solidity|semantic-ui-react|next.js | 64,976 | <p>There is no direct way to convert an Object Promise into a String.
The only way to continue processing is to call an <code>await</code> function or use <code>.then()</code> and a callback function.</p> |
5,233,735 | How to get ASP.NET application path? | <p>I have my owned siteMapProvider, I need phisical file path to initialize it but I can't use HttpContext to do that, because IIS 7 will thrown exception:</p>
<pre><code>fileName = HttpContext.Current.Server.MapPath(fileName);
</code></pre>
<p>How can I do MapPath without HttpContext?</p> | 5,233,768 | 2 | 0 | null | 2011-03-08 14:22:14.277 UTC | 7 | 2013-03-24 20:16:10.587 UTC | 2013-03-24 20:16:10.587 UTC | null | 727,208 | null | 558,457 | null | 1 | 24 | c#|asp.net-mvc | 77,200 | <p>Take a look at the following: <a href="http://msdn.microsoft.com/en-us/library/system.web.httpruntime.appdomainapppath.aspx" rel="noreferrer">HttpRuntime.AppDomainAppPath</a> (from MSDN)</p> |
5,499,003 | SQLite list ALL foreign keys in a database | <p>Is there a way of listing ALL foreign keys in a SQLite database?</p>
<p>They don't seem to be stored in sqlite_master and <code>PRAGMA foreign_key_list('table')</code> only lists one at a time.</p>
<p>Alternatively, is there a way of listing what foreign keys reference a table?</p> | 5,499,071 | 2 | 0 | null | 2011-03-31 11:21:53.673 UTC | 10 | 2019-12-04 11:19:44.813 UTC | 2019-12-04 11:19:44.813 UTC | null | 930,271 | null | 117,433 | null | 1 | 30 | sqlite | 17,390 | <p>With the SQLite shell, use the <code>.schema</code> instruction, and use GREP to filter lines containing <code>REFERENCES</code>.</p>
<p>From <code>shell.c</code> in the SQLite repository, today's version in the trunk, two queries:</p>
<pre><code>SELECT sql
FROM (
SELECT sql sql, type type, tbl_name tbl_name, name name
FROM sqlite_master
UNION ALL
SELECT sql, type, tbl_name, name
FROM sqlite_temp_master
)
WHERE tbl_name LIKE shellstatic()
AND type != 'meta'
AND sql NOTNULL
ORDER BY substr(type, 2, 1), name
</code></pre>
<p>and</p>
<pre><code>SELECT sql
FROM (
SELECT sql sql, type type, tbl_name tbl_name, name name
FROM sqlite_master
UNION ALL
SELECT sql, type, tbl_name, name
FROM sqlite_temp_master
)
WHERE type != 'meta'
AND sql NOTNULL
AND name NOT LIKE 'sqlite_%'
ORDER BY substr(type, 2, 1), name
</code></pre>
<p>The second one is probably what you are looking for.</p> |
5,244,485 | Python code-folding in emacs? | <p>I have many classes and defs ...</p>
<p>I want to have <code>+</code> and <code>-</code> keys before <code>class</code> and <code>def</code> to collapse the class or open it ( toggle it ).</p>
<p>How i can do this? </p> | 17,775,868 | 2 | 5 | null | 2011-03-09 10:34:34.64 UTC | 15 | 2017-07-23 09:54:11.847 UTC | 2017-07-23 09:54:11.847 UTC | null | 1,587,329 | null | 471,397 | null | 1 | 44 | python|emacs|editor|folding | 12,936 | <p>Hideshow works out of the box and folds python code. It is built-in my version of emacs (24.3.1)</p>
<p>I have never needed more than these commands:</p>
<pre><code>M-x hs-minor-mode
M-x hs-hide-all
M-x hs-show-all
</code></pre>
<p>To toggle use C-c @ C-c which probably needs rebinding. You might also want to setup a hook in your .emacs file for hs-minor-mode to automatically be enabled when opening .py files.</p>
<p>I use it in combination the following to jump around.</p>
<pre><code>M-x imenu <my_func_name>
</code></pre> |
16,411,360 | How to inject the same panel into multiple pages using jquery mobile | <p>jQuery Mobile 1.3.1 has a very nice sliding panel feature, but the panel code must be placed within the same page it's used on. </p>
<p>I'm working on an app that needs to have the same panel on many pages. Instead of replicating code is there a way to dynamically inject the panel into these pages so that it will still retain the jqm panel functionality?</p> | 16,414,517 | 4 | 2 | null | 2013-05-07 04:45:51.49 UTC | 11 | 2018-12-11 08:52:02.51 UTC | 2018-12-11 08:52:02.51 UTC | null | 1,033,581 | null | 933,236 | null | 1 | 10 | jquery-mobile | 17,885 | <h2>jQuery Mobile >= 1.4</h2>
<ul>
<li><p><strong>Solution one:</strong></p>
<p>Use an <em>External</em> panel that can be accessed from any page, this is in case you want to have the same panel contents in all pages.</p>
<p>Append panel to <code>$.mobile.pageContainer</code> <strong>once</strong> only on <code>pagebeforecreate</code> and then <em>enhance</em> the panel using <code>$(".selector").panel()</code>.</p>
<pre><code>var panel = '<div data-role="panel" id="mypanel" data-position="right" data-display="push"><h1>Panel</h1><p>stuff</p></div>';
$(document).one('pagebeforecreate', function () {
$.mobile.pageContainer.prepend(panel);
$("#mypanel").panel();
});
</code></pre>
<p>Add button to open the panel in each header (or wherever you want).</p>
<pre><code><a href="#mypanel" class="ui-btn ui-btn-right ui-btn-icon-notext ui-icon-grid ui-corner-all"></a>
</code></pre></li>
</ul>
<p><strong>Note:</strong> When using <em>External Panel</em> <code>data-theme</code> should be added to panel div, as it doesn't inherit any styles/theme. </p>
<blockquote>
<p><strong><a href="http://jsfiddle.net/Palestinian/3qVJw/" rel="nofollow noreferrer">Demo</a></strong></p>
</blockquote>
<hr>
<ul>
<li><p><strong>Solution two:</strong></p>
<p>If you wish to do changes to panel before appending it, based on number of pages in DOM, add panel to each one with a <em>different</em> ID and a button to open that panel.</p>
<p>Note that you don't need to call any kind of enhancement, because you're adding panels on <code>pagebeforecreate</code>. Hence, panels will be auto-initialized once page is <em>created</em>.</p>
<pre><code>var p = 1,
b = 1;
$(document).one('pagebeforecreate', function () {
$.mobile.pageContainer.find("[data-role=page]").each(function () {
var panel = '<div data-role="panel" id="mypanel' + p + '" data-position="right" data-display="push"><h1>Panel</h1><p>stuff</p></div>';
$(this).prepend(panel);
p++;
});
$.mobile.pageContainer.find("[data-role=header]").each(function () {
var panelBtn = '<a href="#mypanel' + b + '" class="ui-btn ui-btn-right ui-btn-icon-notext ui-icon-grid ui-corner-all"></a>'
$(this).append(panelBtn);
b++;
});
});
</code></pre>
<blockquote>
<p><strong><a href="http://jsfiddle.net/Palestinian/7bCU3/" rel="nofollow noreferrer">Demo</a></strong></p>
</blockquote></li>
</ul>
<p><strong>Note:</strong> Make sure you use <code>.one()</code> not <code>.on()</code>, if you use the latter, panels will be added whenever a page is created.</p>
<hr>
<h2>jQuery Mobile <= 1.3</h2>
<p>You can do it this way, using <code>pagebeforecreate</code> event and by checking if there is no Panel added already. Keeping in mind that panels markup should always be placed before <code>[data-role=header]</code> that's why I used <code>.before()</code>.</p>
<p>There is no need to call any <em>enhancement</em> method since <em>panels</em> are added on <code>pagebeforecreate</code>. They will be <em>initialized</em> during that event.</p>
<blockquote>
<p><strong><a href="http://jsfiddle.net/Palestinian/MLBfQ/" rel="nofollow noreferrer">Demo</a></strong></p>
</blockquote>
<p>Your panel</p>
<pre><code>var panel = '<div data-role="panel" id="mypanel" data-position="right" data-display="push"><h1>Panel</h1><p>stuff</p></div>';
</code></pre>
<p>Add panels dynamically</p>
<pre><code>$(document).on('pagebeforecreate', '[data-role=page]', function () {
if ($(this).find('[data-role=panel]').length === 0) {
$('[data-role=header]').before(panel);
}
});
</code></pre>
<hr>
<h2>Update</h2>
<p>There are two <a href="https://stackoverflow.com/a/22636966/1771795">alternative methods</a> to inject "<em>External Panel</em>" dynamically.</p> |
738,546 | Javascript: onrefresh or onreload? | <p>I want an event handler that fires when the user hits reload. Is onrefresh or onreload the correct handler to add to ? Also, will this even fire before or after onunload? Are there an browser inconsistencies? Thanks.</p> | 738,570 | 7 | 0 | null | 2009-04-10 19:03:56.2 UTC | 1 | 2020-07-09 08:42:56.073 UTC | null | null | null | null | 58,109 | null | 1 | 6 | javascript | 50,165 | <p>I don't think there are events called onrefresh or onreload. You can know when the page is unloading, but knowing why (i.e. where the user is going next) is outside JavaScript's security sandbox. The only way to know whether the page has been reloaded is to know where the user was on the last page request, which is also outside the scope of JavaScript. You can sometimes get that via <code>document.referrer</code>, but it relies on the browser's security settings to permit access to that information.</p> |
608,743 | Strategies for recognizing proper nouns in NLP | <p>I'm interested in learning more about <a href="http://en.wikipedia.org/wiki/Natural_language_processing" rel="noreferrer">Natural Language Processing</a> (NLP) and am curious if there are currently any strategies for recognizing proper nouns in a text that aren't based on dictionary recognition? Also, could anyone explain or link to resources that explain the current dictionary-based methods? Who are the authoritative experts on NLP or what are the definitive resources on the subject?</p> | 609,951 | 8 | 0 | null | 2009-03-03 23:56:45.487 UTC | 12 | 2019-03-04 20:00:10.687 UTC | 2010-03-22 18:25:46.273 UTC | VirtuosiMedia | 189,973 | VirtuosiMedia | 13,281 | null | 1 | 14 | nlp|named-entity-recognition|part-of-speech | 7,527 | <p>The task of determining the proper part of speech for a word in a text is called <a href="http://en.wikipedia.org/wiki/POS_tagging" rel="noreferrer">Part of Speech Tagging</a>. The <a href="http://en.wikipedia.org/wiki/Brill_tagger" rel="noreferrer">Brill tagger</a>, for example, uses a mixture of dictionary(vocabulary) words and contextual rules. I believe that some of the important initial dictionary words for this task are the stop words.
Once you have (mostly correct) parts of speech for your words, you can start building larger structures. <a href="http://books.google.com/books?id=jkkoj7U5g4kC&dq=Natural+Language+Processing+for+Online+Applications:+Text+Retrieval,+Extraction+and+Categorization&printsec=frontcover&source=bn&hl=en&ei=GVGuSdebCJDRjAf16p2kBg&sa=X&oi=book_result&resnum=7&ct=result#PPP1,M1" rel="noreferrer">This industry-oriented book</a> differentiates between recognizing noun phrases (NPs) and recognizing named entities.
About textbooks: <a href="https://rads.stackoverflow.com/amzn/click/com/0805303340" rel="noreferrer" rel="nofollow noreferrer">Allen's Natural Language Understanding</a> is a good, but a bit dated, book. <a href="https://rads.stackoverflow.com/amzn/click/com/0262133601" rel="noreferrer" rel="nofollow noreferrer">Foundations of Statistical Natural Language Processing</a> is a nice introduction to statistical NLP. <a href="https://rads.stackoverflow.com/amzn/click/com/0131873210" rel="noreferrer" rel="nofollow noreferrer">Speech and Language Processing</a> is a bit more rigorous and maybe more authoritative. <a href="http://www.aclweb.org/" rel="noreferrer">The Association for Computational Linguistics</a> is a leading scientific community on computational linguistics.</p> |
39,691 | Javascript Best Practices | <p>What are some good resources to learn best practices for Javascript? I'm mainly concerned about when something should be an object vs. when it should just be tracked in the DOM. Also I would like to better learn how to organize my code so it's easy to unit test.</p> | 39,970 | 8 | 1 | 2011-05-20 13:41:29.18 UTC | 2008-09-02 14:41:22.05 UTC | 34 | 2015-09-22 01:02:28.307 UTC | 2008-09-02 14:42:33.857 UTC | blake8086 | 4,114 | blake8086 | 4,114 | null | 1 | 34 | javascript|unit-testing | 6,689 | <p>Seconding <a href="http://oreilly.com/catalog/9780596517748/" rel="noreferrer">Javascript: The Good Parts</a> and Resig's book <a href="http://jsninja.com/" rel="noreferrer">Secrets of the Javascript Ninja</a>.</p>
<p>Here are some tips for Javascript:</p>
<ul>
<li>Don't pollute the global namespace (put all functions into objects/closures)
<ul>
<li>Take a look at <a href="http://developer.yahoo.com/yui/" rel="noreferrer">YUI</a>, it's a huge codebase with only 2 global objects: YAHOO and YAHOO_config</li>
</ul></li>
<li>Use the Module pattern for singletons (<a href="http://yuiblog.com/blog/2007/06/12/module-pattern/" rel="noreferrer">http://yuiblog.com/blog/2007/06/12/module-pattern/</a>)</li>
<li>Make your JS as reusable as possible (jQuery plugins, YUI modules, basic JS objects.) Don't write tons of global functions.</li>
<li>Don't forget to var your variables</li>
<li>Use JSlint : <a href="http://www.jslint.com/" rel="noreferrer">http://www.jslint.com/</a></li>
<li>If you need to save state, it's probably best to use objects instead of the DOM.</li>
</ul> |
83,777 | Are there any Fuzzy Search or String Similarity Functions libraries written for C#? | <p>There are similar question, but not regarding C# libraries I can use in my source code.</p>
<p>Thank you all for your help.</p>
<p>I've already saw lucene, but I need something more easy to search for similar strings and without the overhead of the indexing part.</p>
<p>The answer I marked has got two very easy algorithms, and one uses LINQ too, so it's perfect.</p> | 83,931 | 8 | 1 | null | 2008-09-17 14:24:48.873 UTC | 48 | 2020-02-26 15:31:32.343 UTC | 2014-09-15 14:26:40.6 UTC | volothamp | 1,172,451 | volothamp | 4,206 | null | 1 | 69 | c#|.net|string|comparison | 40,696 | <p>Levenshtein distance implementation: </p>
<ul>
<li><a href="http://www.dotnetperls.com/levenshtein" rel="noreferrer">Using LINQ</a> (not really, see comments) </li>
<li><a href="http://web.archive.org/web/20110720094521/http://www.merriampark.com/ldcsharp.htm" rel="noreferrer">Not using LINQ</a></li>
</ul>
<p>I have a .NET 1.1 project in which I use the latter. It's simplistic, but works perfectly for what I need. From what I remember it needed a bit of tweaking, but nothing that wasn't obvious.</p> |
632,802 | How to deal with Number precision in Actionscript? | <p>I have BigDecimal objects serialized with BlazeDS to Actionscript. Once they hit Actionscript as Number objects, they have values like:</p>
<p><code>140475.32</code> turns into <code>140475.31999999999998</code></p>
<p>How do I deal with this? The problem is that if I use a <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/globalization/NumberFormatter.html" rel="nofollow noreferrer">NumberFormatter</a> with precision of 2, then the value is truncated to <code>140475.31</code>. Any ideas?</p> | 632,914 | 14 | 2 | null | 2009-03-11 00:15:24.48 UTC | 12 | 2017-01-18 11:22:55.493 UTC | 2017-01-18 11:22:55.493 UTC | null | 3,709,765 | Mike S | 16,534 | null | 1 | 18 | apache-flex|actionscript-3|actionscript | 49,766 | <p>This is my generic solution for the problem <em>(I have <a href="http://fraserchapman.blogspot.com/2007/05/rounding-to-specific-decimal-places.html" rel="nofollow noreferrer">blogged about this here</a>)</em>:</p>
<pre><code>var toFixed:Function = function(number:Number, factor:int) {
return Math.round(number * factor)/factor;
}
</code></pre>
<p><em>For example:</em></p>
<pre><code>trace(toFixed(0.12345678, 10)); //0.1
</code></pre>
<ul>
<li>Multiply <code>0.12345678</code> by <code>10</code>; that gives us <code>1.2345678</code>.</li>
<li>When we round <code>1.2345678</code>, we get <code>1.0</code>,</li>
<li>and finally, <code>1.0</code> divided by <code>10</code> equals <code>0.1</code>.</li>
</ul>
<p><em>Another example:</em></p>
<pre><code>trace(toFixed(1.7302394309234435, 10000)); //1.7302
</code></pre>
<ul>
<li>Multiply <code>1.7302394309234435</code> by <code>10000</code>; that gives us <code>17302.394309234435</code>.</li>
<li>When we round <code>17302.394309234435</code> we get <code>17302</code>,</li>
<li>and finally, <code>17302</code> divided by <code>10000</code> equals <code>1.7302</code>.</li>
</ul>
<p><hr>
<strong>Edit</strong></p>
<p>Based on the anonymous answer <a href="https://stackoverflow.com/a/1541929/74861">below</a>, there is a nice simplification for the parameter on the method that makes the precision much more intuitive. <em>e.g:</em></p>
<pre><code>var setPrecision:Function = function(number:Number, precision:int) {
precision = Math.pow(10, precision);
return Math.round(number * precision)/precision;
}
var number:Number = 10.98813311;
trace(setPrecision(number,1)); //Result is 10.9
trace(setPrecision(number,2)); //Result is 10.98
trace(setPrecision(number,3)); //Result is 10.988 and so on
</code></pre>
<p>N.B. I added this here just in case anyone sees this as the answer and doesn't scroll down...</p> |
340,298 | Why are so many web languages interpreted rather than compiled? | <p>Why didn't languages such as C end up being using for web dev? Surely the speed increases from being compiled would be useful for heavy load sites?</p> | 340,327 | 15 | 0 | null | 2008-12-04 11:42:34.127 UTC | 9 | 2017-11-06 00:07:41.497 UTC | 2014-06-25 18:38:18.23 UTC | Joe90 | 578,411 | Rich Bradshaw | 16,511 | null | 1 | 35 | interpreted-language | 11,456 | <p>Another good reason is that on a big server execution speed is not so much an issue as the connection speed anyway. Most of the time is spent sending and receiving data, not number crunching. And actually in certain web services which <em>do</em> a lot of computations, the hard crunching <em>is</em> probably run as a compiled program.</p>
<p>Plus interpreted languages don't need compiling (which on a large project can take time), thus it's more suited for the typically agile development of web solutions. </p> |
192,649 | Can you monkey patch methods on core types in Python? | <p>Ruby can add methods to the Number class and other core types to get effects like this:</p>
<pre class="lang-rb prettyprint-override"><code>1.should_equal(1)
</code></pre>
<p>But it seems like Python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that <em>type</em> can't be modified?</p>
<p><em>Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in Python, would allow this.</em></p>
<p>To answer some of you: The reason I <em>might</em> want to do this is simply aesthetics/readability.</p>
<pre><code> item.price.should_equal(19.99)
</code></pre>
<p>This reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:</p>
<pre><code>should_equal(item.price, 19.99)
</code></pre>
<p>This concept is what <a href="http://rspec.info/" rel="nofollow noreferrer">Rspec</a> and some other Ruby frameworks are based on.</p> | 192,703 | 15 | 3 | null | 2008-10-10 18:56:12.34 UTC | 31 | 2022-06-26 18:51:19.583 UTC | 2022-06-10 16:41:30.22 UTC | toby | 4,621,513 | toby | 5,304 | null | 1 | 55 | python|programming-languages|monkeypatching|fluent-interface | 26,265 | <p>What exactly do you mean by Monkey Patch here? There are <a href="http://wikipedia.org/wiki/Monkey_patch" rel="noreferrer">several slightly different definitions</a>.</p>
<p>If you mean, "can you change a class's methods at runtime?", then the answer is emphatically yes:</p>
<pre><code>class Foo:
pass # dummy class
Foo.bar = lambda self: 42
x = Foo()
print x.bar()
</code></pre>
<p>If you mean, "can you change a class's methods at runtime and <strong>make all of the instances of that class change after-the-fact</strong>?" then the answer is yes as well. Just change the order slightly:</p>
<pre><code>class Foo:
pass # dummy class
x = Foo()
Foo.bar = lambda self: 42
print x.bar()
</code></pre>
<p>But you can't do this for certain built-in classes, like <code>int</code> or <code>float</code>. These classes' methods are implemented in C and there are certain abstractions sacrificed in order to make the implementation easier and more efficient.</p>
<p>I'm not really clear on <strong>why</strong> you would want to alter the behavior of the built-in numeric classes anyway. If you need to alter their behavior, subclass them!!</p> |
861,257 | For kernel/OS is C still it? | <p>I like operating systems and would eventually like to become a OS developer mostly working on kernels. In the future will C still be the language of choice and what else should I be trying to learn?</p> | 861,378 | 17 | 7 | null | 2009-05-14 02:12:50.797 UTC | 11 | 2014-12-13 17:50:29.66 UTC | 2010-03-13 04:55:17.29 UTC | null | 77,914 | null | 106,534 | null | 1 | 19 | operating-system|kernel|osdev | 4,703 | <p>I think it's safe to say that low-level parts of operating systems (e.g. the kernel) will continue to be written in C because of its speed. Like mentioned elsewhere, you will need to know assembler for certain parts of the kernel (something needs to load the kernel into memory). But you can work on the kernel with little or no assembly knowledge. A good example would be if you're implementing a file system.</p>
<p>Don't worry about what language the operating system is implemented in. What's important is how an operating systems are used, and what can be done to improve them. A good example is when Unix first came out. The file system had the inodes at the front of the disk, and data in the remaining space. This didn't perform very well as you were seeking to different parts of the disk for all files. Then the <a href="http://en.wikipedia.org/wiki/Unix_File_System" rel="noreferrer">Berkeley Fast File System</a> was created to make a disk aware file system. This means having inodes near their corresponding data. I'm leaving out a lot of details, but I hope this illustrates that it's more important to think about how an operating system can be improved rather than what language it will be programmed in.</p>
<p>Some recent trends in operating systems are virtualization and distributed computing (see Google's paper on <a href="http://labs.google.com/papers/mapreduce.html" rel="noreferrer">MapReduce</a>). File systems, security, scheduling (especially with multi-core processors), etc are continually areas of interest even though these problems are not new.</p>
<p>Here are some resources if you want to learn more about kernel development:</p>
<ul>
<li><a href="http://kernelnewbies.org/" rel="noreferrer">Linux Kernel Newbies</a> - Resource for those who want to get started on modifying the Linux kernel.</li>
<li><a href="http://pdos.csail.mit.edu/6.828/2008/src/xv6-rev2.tar.gz" rel="noreferrer">xv6 source</a> - x86 port of Unix version 6. Used by MIT to teach an operating systems class. Simple, and easy to extend (<a href="http://pdos.csail.mit.edu/6.828/2008/overview.html" rel="noreferrer">more info</a>).</li>
<li><a href="http://www.makelinux.net/kernel_map" rel="noreferrer">Linux Kernel Map</a> - Call chain of system calls in Linux. Useful in visualizing what a system call does.</li>
</ul>
<p>Bottom line: Start getting familiar with the kernel and read papers on what researchers are writing about (<a href="http://www.usenix.org/" rel="noreferrer">USENIX</a> is useful for this). This knowledge is much more valuable than learning a new language, as most concepts from one language can easily be transferred to another if there does happen to be a shift in what operating systems are written. Hope this helps!</p> |
1,313,120 | Retrieving the last record in each group - MySQL | <p>There is a table <code>messages</code> that contains data as shown below:</p>
<pre><code>Id Name Other_Columns
-------------------------
1 A A_data_1
2 A A_data_2
3 A A_data_3
4 B B_data_1
5 B B_data_2
6 C C_data_1
</code></pre>
<p>If I run a query <code>select * from messages group by name</code>, I will get the result as:</p>
<pre><code>1 A A_data_1
4 B B_data_1
6 C C_data_1
</code></pre>
<p>What query will return the following result?</p>
<pre><code>3 A A_data_3
5 B B_data_2
6 C C_data_1
</code></pre>
<p>That is, the last record in each group should be returned.</p>
<p>At present, this is the query that I use:</p>
<pre><code>SELECT
*
FROM (SELECT
*
FROM messages
ORDER BY id DESC) AS x
GROUP BY name
</code></pre>
<p>But this looks highly inefficient. Any other ways to achieve the same result?</p> | 1,313,293 | 34 | 11 | null | 2009-08-21 17:04:04.147 UTC | 494 | 2022-09-18 18:28:18.117 UTC | 2022-02-22 15:13:40.963 UTC | null | 205,608 | null | 27,474 | null | 1 | 1,243 | mysql|sql|group-by|greatest-n-per-group|groupwise-maximum | 982,266 | <p>MySQL 8.0 now supports <a href="https://dev.mysql.com/doc/refman/8.0/en/window-functions.html" rel="noreferrer">windowing functions</a>, like almost all popular SQL implementations. With this standard syntax, we can write greatest-n-per-group queries:</p>
<pre><code>WITH ranked_messages AS (
SELECT m.*, ROW_NUMBER() OVER (PARTITION BY name ORDER BY id DESC) AS rn
FROM messages AS m
)
SELECT * FROM ranked_messages WHERE rn = 1;
</code></pre>
<p>This and other approaches to finding <a href="https://dev.mysql.com/doc/refman/8.0/en/example-maximum-column-group-row.html" rel="noreferrer">groupwise maximal rows</a> are illustrated in the MySQL manual.</p>
<p>Below is the original answer I wrote for this question in 2009:</p>
<hr />
<p>I write the solution this way:</p>
<pre><code>SELECT m1.*
FROM messages m1 LEFT JOIN messages m2
ON (m1.name = m2.name AND m1.id < m2.id)
WHERE m2.id IS NULL;
</code></pre>
<p>Regarding performance, one solution or the other can be better, depending on the nature of your data. So you should test both queries and use the one that is better at performance given your database.</p>
<p>For example, I have a copy of the <a href="https://archive.org/details/stackexchange" rel="noreferrer">StackOverflow August data dump</a>. I'll use that for benchmarking. There are 1,114,357 rows in the <code>Posts</code> table. This is running on <a href="https://www.mysql.com/" rel="noreferrer">MySQL</a> 5.0.75 on my Macbook Pro 2.40GHz.</p>
<p>I'll write a query to find the most recent post for a given user ID (mine).</p>
<p><strong>First using the technique <a href="https://stackoverflow.com/questions/1313120/sql-retrieving-the-last-record-in-each-group/1313140#1313140">shown</a> by @Eric with the <code>GROUP BY</code> in a subquery:</strong></p>
<pre><code>SELECT p1.postid
FROM Posts p1
INNER JOIN (SELECT pi.owneruserid, MAX(pi.postid) AS maxpostid
FROM Posts pi GROUP BY pi.owneruserid) p2
ON (p1.postid = p2.maxpostid)
WHERE p1.owneruserid = 20860;
1 row in set (1 min 17.89 sec)
</code></pre>
<p>Even the <a href="https://dev.mysql.com/doc/refman/5.7/en/using-explain.html" rel="noreferrer"><code>EXPLAIN</code> analysis</a> takes over 16 seconds:</p>
<pre><code>+----+-------------+------------+--------+----------------------------+-------------+---------+--------------+---------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------+--------+----------------------------+-------------+---------+--------------+---------+-------------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 76756 | |
| 1 | PRIMARY | p1 | eq_ref | PRIMARY,PostId,OwnerUserId | PRIMARY | 8 | p2.maxpostid | 1 | Using where |
| 2 | DERIVED | pi | index | NULL | OwnerUserId | 8 | NULL | 1151268 | Using index |
+----+-------------+------------+--------+----------------------------+-------------+---------+--------------+---------+-------------+
3 rows in set (16.09 sec)
</code></pre>
<p><strong>Now produce the same query result using <a href="https://stackoverflow.com/questions/121387/fetch-the-row-which-has-the-max-value-for-a-column/123481#123481">my technique</a> with <code>LEFT JOIN</code>:</strong></p>
<pre><code>SELECT p1.postid
FROM Posts p1 LEFT JOIN posts p2
ON (p1.owneruserid = p2.owneruserid AND p1.postid < p2.postid)
WHERE p2.postid IS NULL AND p1.owneruserid = 20860;
1 row in set (0.28 sec)
</code></pre>
<p>The <code>EXPLAIN</code> analysis shows that both tables are able to use their indexes:</p>
<pre><code>+----+-------------+-------+------+----------------------------+-------------+---------+-------+------+--------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+----------------------------+-------------+---------+-------+------+--------------------------------------+
| 1 | SIMPLE | p1 | ref | OwnerUserId | OwnerUserId | 8 | const | 1384 | Using index |
| 1 | SIMPLE | p2 | ref | PRIMARY,PostId,OwnerUserId | OwnerUserId | 8 | const | 1384 | Using where; Using index; Not exists |
+----+-------------+-------+------+----------------------------+-------------+---------+-------+------+--------------------------------------+
2 rows in set (0.00 sec)
</code></pre>
<hr />
<p>Here's the DDL for my <code>Posts</code> table:</p>
<pre><code>CREATE TABLE `posts` (
`PostId` bigint(20) unsigned NOT NULL auto_increment,
`PostTypeId` bigint(20) unsigned NOT NULL,
`AcceptedAnswerId` bigint(20) unsigned default NULL,
`ParentId` bigint(20) unsigned default NULL,
`CreationDate` datetime NOT NULL,
`Score` int(11) NOT NULL default '0',
`ViewCount` int(11) NOT NULL default '0',
`Body` text NOT NULL,
`OwnerUserId` bigint(20) unsigned NOT NULL,
`OwnerDisplayName` varchar(40) default NULL,
`LastEditorUserId` bigint(20) unsigned default NULL,
`LastEditDate` datetime default NULL,
`LastActivityDate` datetime default NULL,
`Title` varchar(250) NOT NULL default '',
`Tags` varchar(150) NOT NULL default '',
`AnswerCount` int(11) NOT NULL default '0',
`CommentCount` int(11) NOT NULL default '0',
`FavoriteCount` int(11) NOT NULL default '0',
`ClosedDate` datetime default NULL,
PRIMARY KEY (`PostId`),
UNIQUE KEY `PostId` (`PostId`),
KEY `PostTypeId` (`PostTypeId`),
KEY `AcceptedAnswerId` (`AcceptedAnswerId`),
KEY `OwnerUserId` (`OwnerUserId`),
KEY `LastEditorUserId` (`LastEditorUserId`),
KEY `ParentId` (`ParentId`),
CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`PostTypeId`) REFERENCES `posttypes` (`PostTypeId`)
) ENGINE=InnoDB;
</code></pre>
<hr />
<p><strong>Note to commenters: If you want another benchmark with a different version of MySQL, a different dataset, or different table design, feel free to do it yourself. I have shown the technique above. Stack Overflow is here to show you how to do software development work, not to do all the work for you.</strong></p> |
6,628,358 | The contextual keyword 'var' may only appear within a local variable declaration issues | <p>I know what this means, and I have searched Google, and MSDN. But, how else am I going to get around this?</p>
<p>I have a function in my razor code inside the App_Code folder (using WebMatrix), and I get info from the database, do some calculations, then update the database with the new total.</p>
<p>But, how am I to pass variables to my method in the App_Code folder if it won't let me?</p>
<p>Here's what I've got:</p>
<p>EditQuantity.cshtml (root folder):</p>
<pre><code> try
{
Base baseClass;
baseClass.CalculateTotalPriceInCart(Request.QueryString["PartNumber"], Request.QueryString["Description"], Session["OSFOID"], true);
Response.Redirect("~/Cart.cshtml");
}
catch(Exception exmes)
{
message = exmes;
}
</code></pre>
<p>And, Base.cs (inside App_Code folder):</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using WebMatrix.Data;
/// <summary>
/// Summary description for ClassName
/// </summary>
public class Base
{
public void CalculateTotalPriceInCart(var PartNumber, var Description, var OrderId, bool IsBoxed)
{
var database = Database.Open("OSF");
var query = "";
var result = "";
decimal price = 0.00M;
if(IsBoxed)
{
// Select item.
query = "SELECT Boxes, BoxPrice FROM Cart WHERE OrderId = '" + OrderId + "' AND PartNumber = '" + PartNumber + "' AND Description = '" + Description + "' AND IsBoxed = 1";
result = database.Query(query);
// Recalculate Price.
foreach(var item in result)
{
price = result.Boxes * result.BoxPrice;
}
// Update item.
query = "UPDATE Cart SET BoxPrice = '" + price + "' WHERE OrderId = '" + OrderId + "' AND PartNumber = '" + PartNumber + "' AND Description = '" + Description + "' AND IsBoxed = 1";
database.Execute(query);
}
}
}
</code></pre>
<p>I've tried a few things to see if it'd work, but nope. I'm obviously doing it wrong, but this is how I do it in Desktop apps, I don't get why it'd be different here for WebPages, and how shold I go about doing this?</p>
<p>Thank you!</p> | 6,628,388 | 5 | 1 | null | 2011-07-08 17:50:55.587 UTC | 2 | 2021-03-07 01:03:12.247 UTC | 2011-07-08 20:28:33.527 UTC | null | 358,970 | null | 789,564 | null | 1 | 8 | c#|.net|webmatrix | 40,340 | <p>You can't define method parameters with the var keyword because the compiler cannot determine the method signature at compile time. </p>
<pre><code>public void CalculateTotalPriceInCart(
string Description,
string PartNumber,
string OrderId,
bool IsBoxed)
</code></pre>
<p>In another comment you said it can't cast <code>IEnumerable<dynamic></code> to a <code>string</code>. So declare the parameter properly! I don't know which it is. </p>
<pre><code>public void CalculateTotalPriceInCart(
IEnumerable<dynamic> Description, // for example
string PartNumber,
string OrderId,
bool IsBoxed)
</code></pre> |
6,946,660 | Windows batch file does not wait for commands to complete | <p>I have a batch file, which exists as soon as start it (run as admin) and does not execute commands that are in it, but if I specify it at the command-line, it runs fine and executes all commands. </p>
<p>Here's what's in it:</p>
<pre><code>start /wait msiexec /x SetupServices.msi /qn /l* "SetupServices.uninstall.log"
start /wait msiexec /i SetupServices.msi /qn /l* "SetupServices.install.log"
</code></pre> | 17,773,931 | 6 | 0 | null | 2011-08-04 18:29:21.497 UTC | 3 | 2021-04-27 04:43:54.74 UTC | 2013-08-17 20:09:11.923 UTC | null | 572,834 | null | 2,654,100 | null | 1 | 6 | command-line|windows-installer | 45,745 | <p>(Corrected answer)</p>
<p>First, if you start .exe files in a batch, it is safer, to prefix it with "call".
Sometimes this is necessary to assure, that the batch is waiting to complete.</p>
<p>Using "start" is another possibility, but for this simple usecase not necessary.</p>
<p>You write that the commands are <em>not</em> executed. So, obviously, you have another problem, instead of the "does not wait.. to complete" problem.
Taking a look of your newly provided example, this is the case. In admin mode, you have to provide a full path. With my small trick below ("%~dp0", including already backslash), you can still use the current directory in batchfiles.</p>
<p>Most times, if such a problem occurs with admin rights, this is a problem of the "current directory" path. A batch file with admin rights is not using it in the same way as we were used to, it does not start in it's own directory (but in System32 mostly). Not relying on the CD is an important matter of writing bullet-proof batch files.</p>
<p>A good example batch , combining other answers here, and solving a number of possible problems in your case is:</p>
<pre><code>call msiexec /i "%~dp0MySetup.msi" /qb /L*v "%~dp0MySetup.log"
echo Returncode: %ERRORLEVEL%
pause
</code></pre>
<p>It uses the current directory correctly, and assumes an install commandline including a logfile (works only, if you have write access in the current directory, if not specify a path for the logfile with write access like "%TEMP%\MySetup.log".</p>
<p>Attention: Remember to really start the batch file with admin rights (right mouse menu or opening an admin command shell before:)</p> |
6,394,416 | Replace tabs and spaces with a single space as well as carriage returns and newlines with a single newline | <pre><code>$string = "My text has so much whitespace
Plenty of spaces and tabs";
echo preg_replace("/\s\s+/", " ", $string);
</code></pre>
<p>I read the PHP's documentation and followed the <code>preg_replace()</code> tutorial, however this code produces:</p>
<pre><code>My text has so much whitespace Plenty of spaces and tabs
</code></pre>
<p>How can I turn it into :</p>
<pre><code>My text has so much whitespace
Plenty of spaces and tabs
</code></pre> | 6,394,462 | 11 | 2 | null | 2011-06-18 06:57:56.357 UTC | 16 | 2022-03-28 11:47:36.243 UTC | 2022-03-28 11:24:09.697 UTC | null | 2,943,403 | null | 433,531 | null | 1 | 41 | php|regex|preg-replace|whitespace | 74,440 | <p>First, I'd like to point out that new lines can be either \r, \n, or \r\n depending on the operating system.</p>
<p>My solution:</p>
<pre><code>echo preg_replace('/[ \t]+/', ' ', preg_replace('/[\r\n]+/', "\n", $string));
</code></pre>
<p>Which could be separated into 2 lines if necessary:</p>
<pre><code>$string = preg_replace('/[\r\n]+/', "\n", $string);
echo preg_replace('/[ \t]+/', ' ', $string);
</code></pre>
<p><strong>Update</strong>:</p>
<p>An even better solutions would be this one:</p>
<pre><code>echo preg_replace('/[ \t]+/', ' ', preg_replace('/\s*$^\s*/m', "\n", $string));
</code></pre>
<p>Or:</p>
<pre><code>$string = preg_replace('/\s*$^\s*/m', "\n", $string);
echo preg_replace('/[ \t]+/', ' ', $string);
</code></pre>
<p>I've changed the regular expression that makes multiple lines breaks into a single better. It uses the "m" modifier (which makes ^ and $ match the start and end of new lines) and removes any \s (space, tab, new line, line break) characters that are a the end of a string and the beginning of the next. This solve the problem of empty lines that have nothing but spaces. With my previous example, if a line was filled with spaces, it would have skipped an extra line.</p> |
6,471,959 | jQuery UI Datepicker onchange event issue | <p>I have a JS code in which when you change a field it calls a search routine. The problem is that I can't find any jQuery events that will fire when the Datepicker updates the input field.</p>
<p>For some reason, a change event is not called when Datepicker updates the field. When the calendar pops up it changes the focus so I can't use that either. Any ideas?</p> | 6,471,992 | 18 | 1 | null | 2011-06-24 18:06:25.523 UTC | 34 | 2022-07-02 18:16:22.537 UTC | 2022-07-02 18:16:22.537 UTC | null | 1,141,275 | null | 760,092 | null | 1 | 261 | jquery|datepicker|jquery-ui-datepicker | 654,082 | <p>You can use the datepicker's <a href="https://api.jqueryui.com/datepicker/#option-onSelect" rel="noreferrer"><code>onSelect</code> event</a>.</p>
<pre><code>$(".date").datepicker({
onSelect: function(dateText) {
console.log("Selected date: " + dateText + "; input's current value: " + this.value);
}
});
</code></pre>
<p><strong>Live example</strong>:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(".date")
.datepicker({
onSelect: function(dateText) {
console.log("Selected date: " + dateText + "; input's current value: " + this.value);
}
})
.on("change", function() {
console.log("Got change event from field");
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<input type='text' class='date'>
<script src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script></code></pre>
</div>
</div>
</p>
<p>Unfortunately, <code>onSelect</code> fires whenever a date is selected, even if it hasn't changed. This is a design flaw in the datepicker: It always fires <code>onSelect</code> (even if nothing changed), and <em>doesn't</em> fire any event on the underlying input on change. (If you look in the code of that example, we're listening for changes, but they aren't being raised.) It should probably fire an event on the input when things change (possibly the usual <code>change</code> event, or possibly a datepicker-specific one).</p>
<hr />
<p>If you like, of course, you can make the <code>change</code> event on the <code>input</code> fire:</p>
<pre><code>$(".date").datepicker({
onSelect: function() {
$(this).change();
}
});
</code></pre>
<p>That will fire <code>change</code> on the underlying <code>input </code>for any handler hooked up via jQuery. But again, it <em>always</em> fires it. If you want to only fire on a real change, you'll have to save the previous value (possibly via <code>data</code>) and compare.</p>
<p><strong>Live example</strong>:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(".date")
.datepicker({
onSelect: function(dateText) {
console.log("Selected date: " + dateText + "; input's current value: " + this.value);
$(this).change();
}
})
.on("change", function() {
console.log("Got change event from field");
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<input type='text' class='date'>
<script src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script></code></pre>
</div>
</div>
</p> |
6,605,006 | Convert PDF to image with high resolution | <p>I'm trying to use the command line program <a href="http://www.imagemagick.org/script/convert.php" rel="noreferrer"><code>convert</code></a> to take a PDF into an image (JPEG or PNG). Here is <a href="http://jonathanwhitmore.com/wp-content/uploads/2011/07/test.pdf" rel="noreferrer" title="one of the pdfs">one of the PDFs</a> that I'm trying to convert. </p>
<p>I want the program to trim off the excess white-space and return a high enough quality image that the superscripts can be read with ease.</p>
<p>This is my current <a href="https://i.stack.imgur.com/FCjw6.jpg" rel="noreferrer">best attempt</a>. As you can see, the trimming works fine, I just need to sharpen up the resolution quite a bit. This is the command I'm using: </p>
<pre><code>convert -trim 24.pdf -resize 500% -quality 100 -sharpen 0x1.0 24-11.jpg
</code></pre>
<p>I've tried to make the following conscious decisions:</p>
<ul>
<li>resize it larger (has no effect on the resolution)</li>
<li>make the quality as high as possible</li>
<li>use the <code>-sharpen</code> (I've tried a range of values)</li>
</ul>
<p>Any suggestions please on getting the resolution of the image in the final PNG/JPEG higher would be greatly appreciated!</p> | 6,605,085 | 23 | 5 | null | 2011-07-07 01:52:36.78 UTC | 175 | 2022-08-16 02:47:15.817 UTC | 2018-07-08 13:44:06.693 UTC | null | 246,856 | null | 246,856 | null | 1 | 395 | pdf|imagemagick | 430,697 | <p>It appears that the following works: </p>
<pre><code>convert \
-verbose \
-density 150 \
-trim \
test.pdf \
-quality 100 \
-flatten \
-sharpen 0x1.0 \
24-18.jpg
</code></pre>
<p>It results in <a href="https://i.stack.imgur.com/qmLXI.jpg" rel="noreferrer"><strong>the left image</strong></a>. Compare this to the result of my original command (<a href="https://i.stack.imgur.com/FCjw6.jpg" rel="noreferrer"><strong>the image on the right</strong></a>):</p>
<p><img src="https://i.stack.imgur.com/qmLXI.jpg" width="310"> <img src="https://i.stack.imgur.com/FCjw6.jpg" width="310"></p>
<p>(To <strong><em>really</em></strong> see and appreciate the differences between the two, right-click on each and select <em>"Open Image in New Tab..."</em>.)</p>
<p>Also keep the following facts in mind:</p>
<ul>
<li>The worse, blurry image on the right has a file size of 1.941.702 Bytes (1.85 MByte).
Its resolution is 3060x3960 pixels, using 16-bit RGB color space.</li>
<li>The better, sharp image on the left has a file size of 337.879 Bytes (330 kByte).
Its resolution is 758x996 pixels, using 8-bit Gray color space.</li>
</ul>
<p>So, no need to resize; add the <code>-density</code> flag. The density value 150 is weird -- trying a range of values results in a worse looking image in both directions!</p> |
15,881,959 | 3D Plotting from X, Y, Z Data, Excel or other Tools | <p>I have data that looks like this:</p>
<pre><code>1000 13 75.2
1000 21 79.21
1000 29 80.02
5000 29 87.9
5000 37 88.54
5000 45 88.56
10000 29 90.11
10000 37 90.79
10000 45 90.87
</code></pre>
<p>I want to use the first column as x axis labels, the second column as y axis labels and the third column as the z values. I want to display a surface in that manner. What is the best way to do this? I tried Excel but didn't really get anywhere. Does anyone have any suggestions for a tool to do this? Does anyone know how to do this in Excel?</p>
<p>Thanks</p> | 15,914,872 | 5 | 0 | null | 2013-04-08 14:36:33.293 UTC | 3 | 2019-04-27 03:03:40.997 UTC | 2014-06-22 03:15:58.803 UTC | null | 168,175 | null | 1,698,695 | null | 1 | 16 | excel|charts|plot|visualization|data-visualization | 140,974 | <p>I ended up using <a href="http://matplotlib.org/" rel="nofollow noreferrer">matplotlib</a> :)</p>
<pre><code>from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
x = [1000,1000,1000,1000,1000,5000,5000,5000,5000,5000,10000,10000,10000,10000,10000]
y = [13,21,29,37,45,13,21,29,37,45,13,21,29,37,45]
z = [75.2,79.21,80.02,81.2,81.62,84.79,87.38,87.9,88.54,88.56,88.34,89.66,90.11,90.79,90.87]
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.2)
plt.show()
</code></pre> |
15,689,471 | Is it possible to Command-click a symbol into a new tab in Xcode? | <p>I am searching for a keyboard shortcut that allows me to combine 'Cmd-t' (open new tab) and 'Cmd-click on a symbol' (jump to definition). I want to be able to open the symbol definition in a new tab, much like Cmd-click (Ctrl-click on Windows) opens a link in a new tab when using a web browser.</p>
<p>I tried some different combinations but have given up after Cmd-option-Shift-click crashed Xcode!</p>
<p>I'm currently using Xcode 4.6.1.</p> | 21,237,084 | 4 | 0 | null | 2013-03-28 18:26:48.827 UTC | 4 | 2015-08-04 07:55:19.07 UTC | null | null | null | null | 869,936 | null | 1 | 32 | xcode|keyboard-shortcuts|hotkeys | 6,657 | <ol>
<li>Go to XCode->Preferences, </li>
<li>Select Navigation tab, </li>
<li>Change "Double Click Navigation" to "Uses Separate Tab"</li>
</ol>
<p>Now command-double-click the symbol to open in new tab.</p> |
50,565,724 | Are test suites considered deprecated in JUnit5? | <p>
I am trying to create test suites with JUnit5. After some research I was not able to conclude whether it is a supported feature or not.</p>
<p>The <a href="https://junit.org/junit5/docs/current/user-guide/#running-tests-junit-platform-runner-test-suite" rel="noreferrer">official user guide</a> only mentions suites with regard to backwards compatibility to JUnit 4.</p>
<p>This is how it was done back in JUnit 4:</p>
<pre class="lang-java prettyprint-override"><code>@RunWith(Suite.class)
@SuiteClasses({Test1.class, Test2.class})
public class TestSuite {
}
</code></pre>
<p>Does this mean, that Test Suites are considered deprecated now, or is the same concept still available under another name?</p> | 50,678,092 | 2 | 6 | null | 2018-05-28 11:48:34.963 UTC | 3 | 2022-05-19 15:25:00.64 UTC | 2018-06-04 09:30:33.563 UTC | null | 388,980 | null | 9,142,258 | null | 1 | 39 | java|junit|junit5|test-suite | 16,934 | <blockquote>
<p>Does this mean, that Test Suites are considered deprecated now, or is the same concept still available under another name?</p>
</blockquote>
<p><strong>Bitter <em>Suite</em> Answer:</strong></p>
<p>There is in fact support for test suites in JUnit 5, but it's almost certainly not what you're looking for. However, the JUnit Team is working on something that will likely suit your needs.</p>
<p><strong>Detailed Answer:</strong></p>
<p>As of JUnit 5.2, the only built-in support for <em>suites</em> is via the <code>JUnitPlatform</code> <em>Runner</em> (registered via <code>@RunWith(JUnitPlatform.class)</code>). That runner actually launches the JUnit Platform (a.k.a., JUnit 5 infrastructure) and allows you to execute tests against various programming models such as JUnit 4 and JUnit Jupiter. It also allows you to select various things (e.g., classes, packages, etc.) and configure include and exclude filters (e.g., for tags or test engines).</p>
<p>The problem with the runner is that it can <strong>not</strong> be executed directly on the JUnit Platform. It can <em>only</em> be executed using JUnit 4 by itself. That means that you lose the full reporting capabilities of the JUnit Platform since information is lost in translation from the JUnit Platform to JUnit 4.</p>
<p>In summary, you can technically use the <code>JUnitPlatform</code> runner to execute a suite using JUnit 5, and the tests will execute, but the reporting and display in an IDE will be suboptimal.</p>
<p>On the bright side, the JUnit Team plans to provide built-in support for suites in JUnit 5 that does not suffer from the shortcomings of the <code>JUnitPlatform</code> runner for JUnit 4. For details, see all issues assigned to the <a href="https://github.com/junit-team/junit5/labels/theme%3A%20suites" rel="noreferrer">"suites" label on GitHub</a>.</p>
<p>In addition, there is already a <a href="https://github.com/junit-team/junit5/compare/experiments/platform-suites" rel="noreferrer">feature branch</a> that you can check out which can be <a href="https://jitpack.io/#junit-team/junit5/experiments~platform-suites-SNAPSHOT" rel="noreferrer">consumed in a Maven or Gradle build via JitPack</a>.</p>
<p>Regards,</p>
<p>Sam (JUnit 5 core committer)</p> |
10,790,737 | Why would code actively try to prevent tail-call optimization? | <p>The title of the question might be a bit strange, but the thing is that, as far as I know, there is nothing that speaks against tail call optimization at all. However, while browsing open source projects, I already came across a few functions that actively try to stop the compiler from doing a tail call optimization, for example the implementation of <a href="http://opensource.apple.com/source/CF/CF-635.21/CFRunLoop.c" rel="noreferrer">CFRunLoopRef</a> which is full of such <em>hacks</em>. For example:</p>
<pre><code>static void __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__() __attribute__((noinline));
static void __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(CFRunLoopObserverCallBack func, CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) {
if (func) {
func(observer, activity, info);
}
getpid(); // thwart tail-call optimization
}
</code></pre>
<p>I would love to know why this is seemingly so important, and are there any cases were I as a <em>normal</em> developer should keep this is mind too? Eg. are there common pitfalls with tail call optimization?</p> | 10,790,864 | 3 | 17 | null | 2012-05-28 21:46:37.503 UTC | 11 | 2014-01-06 12:04:28.523 UTC | 2012-05-28 22:14:28.057 UTC | null | 15,168 | null | 350,272 | null | 1 | 81 | c++|c|optimization|compiler-optimization|tail-call-optimization | 3,342 | <p>My guess here is that it's to ensure that <code>__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__</code> is in the stack trace for debugging purposes. It has <code>__attribute__((no inline))</code> which backs up this idea.</p>
<p>If you notice, that function just goes and bounces to another function anyway, so it's a form of trampoline which I can only think is there with such a verbose name to aid debugging. This would be especially helpful given that the function is calling a function pointer that has been registered from elsewhere and therefore that function may not have debugging symbols accessible. </p>
<p>Notice also the other similarly named functions which do similar things - it really looks like it's there to aid in seeing what has happened from a backtrace. Keep in mind that this is core Mac OS X code and will show up in crash reports and process sample reports too.</p> |
35,536,590 | Do I need to escape dash character in regex? | <p>I'm trying to understand dash character <code>-</code> needs to escape using backslash in regex?</p>
<p>Consider this:</p>
<pre><code>var url = '/user/1234-username';
var pattern = /\/(\d+)\-/;
var match = pattern.exec(url);
var id = match[1]; // 1234
</code></pre>
<p>As you see in the above regex, I'm trying to extract the number of id from the url. Also I escaped <code>-</code> character in my regex using backslash <code>\</code>. But when I remove that backslash, still all fine ....! In other word, both of these are fine:</p>
<ul>
<li><a href="https://regex101.com/r/sJ5mX4/1" rel="noreferrer"><code>/\/(\d+)\-/</code></a></li>
<li><a href="https://regex101.com/r/sJ5mX4/2" rel="noreferrer"><code>/\/(\d+)-/</code></a></li>
</ul>
<p>Now I want to know, which one is correct <em>(standard)</em>? Do I need to escape dash character in regex? </p> | 35,536,652 | 2 | 6 | null | 2016-02-21 13:15:08.12 UTC | 1 | 2022-07-31 20:34:55.14 UTC | null | null | null | null | 2,805,376 | null | 1 | 33 | javascript|regex | 37,288 | <p>You only need to escape the dash character if it could otherwise be interpreted as a range indicator (which can be the case inside a <a href="http://www.regular-expressions.info/charclass.html" rel="noreferrer">character class</a>).</p>
<pre><code>/-/ # matches "-"
/[a-z]/ # matches any letter in the range between ASCII a and ASCII z
/[a\-z]/ # matches "a", "-" or "z"
/[a-]/ # matches "a" or "-"
/[-z]/ # matches "-" or "z"
</code></pre> |
13,281,197 | Android - How to create clickable listview? | <p>I want to make all my list items in the listview open up into a new page, so each listview item opens up onto a new black page that I can use. I don't know how to implement this at all. I have searched for hours on end and can't find an answer to my solution. It would be much appreciated if someone could show and/or explain how to do this instead of providing a link, but either is helpful.</p>
<p>Here is my code so far:</p>
<pre><code> <string-array name="sections">
<item >Pro Constructive</item>
<item >Con Constructive</item>
<item >1st Speaker Cross</item>
<item >Pro Rebbutal</item>
<item >Con Rebuttal</item>
<item >2nd Speaker Cross</item>
<item >Pro Summary</item>
<item >Con Summary</item>
<item >Grand Cross</item>
<item >Pro Final Focus</item>
<item >Con Final Focus</item>
</string-array>
</code></pre>
<p>This is in my string.xml</p>
<pre><code> <ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:entries="@array/sections" >
</ListView>
</code></pre>
<p>This is in my activity_main.xml.</p>
<p>Where do I go from here to make each item in my list clickable and able to open up onto a new page?</p>
<p>Thanks in advance!</p>
<p>EDIT:</p>
<p>Logcat no longer relevant.</p> | 13,281,256 | 5 | 0 | null | 2012-11-08 01:37:20.13 UTC | 4 | 2019-09-09 10:19:09.44 UTC | 2012-11-09 03:20:06.36 UTC | null | 1,457,559 | null | 1,457,559 | null | 1 | 14 | java|android|eclipse|listview|clickable | 54,855 | <p>In fact it is quite easy:</p>
<p>This is your Activity with the ListView, it implements an OnItemClickListener:</p>
<pre><code>public class MainActivity extends Activity implements OnItemClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//* *EDIT* *
ListView listview = (ListView) findViewById(R.id.listView1);
listview.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
Log.i("HelloListView", "You clicked Item: " + id + " at position:" + position);
// Then you start a new Activity via Intent
Intent intent = new Intent();
intent.setClass(this, ListItemDetail.class);
intent.putExtra("position", position);
// Or / And
intent.putExtra("id", id);
startActivity(intent);
}
</code></pre>
<p><b>Edit</b></p>
<p>The above code would be placed in your MainActivity.java. I changed the name of the class to <code>MainActivity</code> and the contentView to <code>setContentView(R.layout.activity_main)</code> - The names are those of a freshly created Android Project in Eclipse. <br>Please see also the 2 new lines under //* <em>Edit</em> * - those will set the Listener for clicks on items in the list.</p>
<p>Your activity_main.xml should look like this:</p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:entries="@array/sections" >
</ListView>
</RelativeLayout>
</code></pre>
<p>The <b>array.xml</b> (not string.xml) in your `res/values/` folder looks like this</p>
<pre><code><resources>
<string-array name="sections">
<item >Pro Constructive</item>
<item >Con Constructive</item>
<item >1st Speaker Cross</item>
<item >Pro Rebbutal</item>
<item >Con Rebuttal</item>
<item >2nd Speaker Cross</item>
<item >Pro Summary</item>
<item >Con Summary</item>
<item >Grand Cross</item>
<item >Pro Final Focus</item>
<item >Con Final Focus</item>
</string-array>
</resources>
</code></pre>
<p>N.B.: If you copy & paste this code it should work. But you will get an error by clicking on an Item because you haven't created the <code>ListItemDetail.class</code> yet.<p>Here is an example of how this could look:</p></p>
<p>Your ListItemDetail.java:</p>
<pre><code>public class ListItemDetail extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listitem);
Intent intent = getIntent();
int position = intent.getIntExtra("position", 0);
// Here we turn your string.xml in an array
String[] myKeys = getResources().getStringArray(R.array.sections);
TextView myTextView = (TextView) findViewById(R.id.my_textview);
myTextView.setText(myKeys[position]);
}
}
</code></pre>
<p>And its activity_listitem.xml</p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/my_textview"/>
</LinearLayout>
</code></pre>
<p>If you copy past this code it will work.</p> |
13,321,980 | Yet Another MinGW "gcc: error: CreateProcess: No such file or directory" | <p>I have installed MinGW C compiler in Windows 8 (64 bit) through the GUI installer.
But when I try to compile a C program, gcc says: <strong>gcc: CreateProcess: No such file or directory</strong></p>
<p>It is a common bug, and I have tried all the solutions I found, without success.</p>
<p>In particular, (following <a href="https://stackoverflow.com/questions/3848357/gcc-createprocess-no-such-file-or-directory">CreateProcess: No such file or directory</a>) I have tried to:</p>
<ol>
<li>[EDITED] Add <strong>C:\MinGw\libexec\gcc\mingw32\4.7.2</strong> to my system PATH </li>
<li><p>Uninstall and re-install gcc through mingw-get CLI:</p>
<p>mingw-get remove mingw32-gcc<br>
mingw-get install mingw32-gcc</p></li>
</ol>
<p>Other suggestions?</p>
<p>EDIT: verbose gcc output:</p>
<pre><code>> gcc -v helloWorld.c
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=c:/mingw/bin/../libexec/gcc/mingw32/4.7.2/lto-
wrapper.exe
Target: mingw32
Configured with: ../gcc-4.7.2/configure --enable-languages=c,c++,ada,fortran,obj
c,obj-c++ --disable-sjlj-exceptions --with-dwarf2 --enable-shared --enable-libgo
mp --disable-win32-registry --enable-libstdcxx-debug --disable-build-poststage1-
with-cxx --enable-version-specific-runtime-libs --build=mingw32 --prefix=/mingw
Thread model: win32
gcc version 4.7.2 (GCC)
COLLECT_GCC_OPTIONS='-v' '-mtune=i386' '-march=i386'
cc1plus -quiet -v -iprefix c:\mingw\bin\../lib/gcc/mingw32/4.7.2/
OPTIONS.C -quiet -dumpbase OPTIONS.C -mtune=i386 -march=i386 -auxbase OPTIONS -
version -o C:\Users\elvis\AppData\Local\Temp\cc4fWSvg.s
gcc: error: CreateProcess: No such file or directory
</code></pre> | 13,326,306 | 8 | 15 | null | 2012-11-10 12:17:44.527 UTC | 6 | 2017-11-23 03:16:47.087 UTC | 2017-05-23 11:33:16.553 UTC | null | -1 | null | 1,507,699 | null | 1 | 15 | c|gcc|windows-8|mingw | 42,129 | <p>You shouldn't add <code>C:\MinGw\libexec\gcc\mingw32\4.7.2</code> to the path.</p>
<p>Add: <code>c:\MinGW\bin</code></p>
<p>You may need to reboot to ensure that the path is made available to all processes properly.</p>
<p>Another suggestion is to use a different MinGW distribution. It's been a long time since I used an 'official' MinGW distribution because the installation steps were so byzantine and fragile. I've heard they've made large advances to the installer, but from what I hear it still seems to be rather complicated and fragile.</p>
<p><a href="http://tdm-gcc.tdragon.net/download">TDM's installer</a> just works, but I think the TDM release isn't quite to 4.7.2.</p>
<p>The <a href="http://nuwen.net/mingw.html">nuwen distribution's</a> installation is just unpacking an archive where you want the thing (I love that!) and making sure the path points to the location of gcc.exe. Nuwen also packages the boost libraries, which is nice.</p>
<hr>
<p>I case it helps, here's what I get from <code>gcc -v hello.c</code> (<code>c:\mingw.4.7.2\bin</code> is in the path`):</p>
<pre><code>Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=c:/mingw.4.7.2/bin/../libexec/gcc/i686-pc-mingw32/4.7.2/lto-wrapper.exe
Target: i686-pc-mingw32
Configured with: ../src/configure --prefix=/c/temp/gcc/dest --with-gmp=/c/temp/gcc/gmp --with-mpfr=/c/temp/gcc/mpfr --with-mpc=/c/temp/gcc/mpc --enable-languages=c,c++ --with-arch=i686 --with-tune=generic --disable-libstdcxx-pch --disable-nls --disable-shared --disable-sjlj-exceptions --disable-win32-registry --enable-checking=release --enable-lto
Thread model: win32
gcc version 4.7.2 (GCC)
COLLECT_GCC_OPTIONS='-v' '-mtune=generic' '-march=i686'
c:/mingw.4.7.2/bin/../libexec/gcc/i686-pc-mingw32/4.7.2/cc1.exe -quiet -v -iprefix c:\mingw.4.7.2\bin\../lib/gcc/i686-pc-mingw32/4.7.2/ hello.c -quiet -dumpbase hello.c -mtune=generic -march=i686 -auxbase hello -version -o C:\Users\mikeb\AppData\Local\Temp\cct1oltc.s
GNU C (GCC) version 4.7.2 (i686-pc-mingw32)
compiled by GNU C version 4.7.2, GMP version 5.0.5, MPFR version 3.1.1-p2, MPC version 1.0.1
GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
ignoring nonexistent directory "c:\mingw.4.7.2\bin\../lib/gcc/i686-pc-mingw32/4.7.2/../../../../i686-pc-mingw32/include"
ignoring duplicate directory "c:/mingw.4.7.2/lib/gcc/../../lib/gcc/i686-pc-mingw32/4.7.2/include"
ignoring nonexistent directory "c:/temp/gcc/dest/include"
ignoring nonexistent directory "/c/temp/gcc/dest/include"
ignoring duplicate directory "c:/mingw.4.7.2/lib/gcc/../../lib/gcc/i686-pc-mingw32/4.7.2/include-fixed"
ignoring nonexistent directory "c:/mingw.4.7.2/lib/gcc/../../lib/gcc/i686-pc-mingw32/4.7.2/../../../../i686-pc-mingw32/include"
ignoring nonexistent directory "/mingw/include"
#include "..." search starts here:
#include <...> search starts here:
c:\mingw.4.7.2\bin\../lib/gcc/i686-pc-mingw32/4.7.2/include
c:\mingw.4.7.2\bin\../lib/gcc/i686-pc-mingw32/4.7.2/../../../../include
c:\mingw.4.7.2\bin\../lib/gcc/i686-pc-mingw32/4.7.2/include-fixed
End of search list.
GNU C (GCC) version 4.7.2 (i686-pc-mingw32)
compiled by GNU C version 4.7.2, GMP version 5.0.5, MPFR version 3.1.1-p2, MPC version 1.0.1
GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
Compiler executable checksum: 8461a53e6fc78ff58191bda61fe9586d
COLLECT_GCC_OPTIONS='-v' '-mtune=generic' '-march=i686'
as -v -o C:\Users\mikeb\AppData\Local\Temp\ccqRcYAj.o C:\Users\mikeb\AppData\Local\Temp\cct1oltc.s
GNU assembler version 2.22 (i686-pc-mingw32) using BFD version (GNU Binutils) 2.22
COMPILER_PATH=c:/mingw.4.7.2/bin/../libexec/gcc/i686-pc-mingw32/4.7.2/;c:/mingw.4.7.2/bin/../libexec/gcc/
LIBRARY_PATH=c:/mingw.4.7.2/bin/../lib/gcc/i686-pc-mingw32/4.7.2/;c:/mingw.4.7.2/bin/../lib/gcc/;c:/mingw.4.7.2/bin/../lib/gcc/i686-pc-mingw32/4.7.2/../../../
COLLECT_GCC_OPTIONS='-v' '-mtune=generic' '-march=i686'
c:/mingw.4.7.2/bin/../libexec/gcc/i686-pc-mingw32/4.7.2/collect2.exe -Bdynamic c:/mingw.4.7.2/bin/../lib/gcc/i686-pc-mingw32/4.7.2/../../../crt2.o c:/mingw.4.7.2/bin/../lib/gcc/i686-pc-mingw32/4.7.2/crtbegin.o -Lc:/mingw.4.7.2/bin/../lib/gcc/i686-pc-mingw32/4.7.2 -Lc:/mingw.4.7.2/bin/../lib/gcc -Lc:/mingw.4.7.2/bin/../lib/gcc/i686-pc-mingw32/4.7.2/../../.. C:\Users\mikeb\AppData\Local\Temp\ccqRcYAj.o -lmingw32 -lgcc -lmoldname -lmingwex -lmsvcrt -ladvapi32 -lshell32 -luser32 -lkernel32 -lmingw32 -lgcc -lmoldname -lmingwex -lmsvcrt c:/mingw.4.7.2/bin/../lib/gcc/i686-pc-mingw32/4.7.2/crtend.o
</code></pre> |
13,398,462 | Unpickling python objects with a changed module path | <p>I'm trying to integrate a project <code>Project A</code> built by a colleague into another python project. Now this colleague has not used relative imports in his code but instead done</p>
<pre><code>from packageA.moduleA import ClassA
from packageA.moduleA import ClassB
</code></pre>
<p>and consequently pickled the classes with <code>cPickle</code>. For neatness I'd like to hide the package that his (<code>Project A</code>) built inside my project. This however changes the path of the classes defined in <code>packageA</code>. No problem, I'll just redefine the import using</p>
<pre><code>from ..packageA.moduleA import ClassA
from ..packageA.moduleA import ClassB
</code></pre>
<p>but now the un pickling the classes fails with the following message</p>
<pre><code> with open(fname) as infile: self.clzA = cPickle.load(infile)
ImportError: No module named packageA.moduleA
</code></pre>
<p>So why doesn't <code>cPickle</code> apparently see the module defs. Do I need to add the root of <code>packageA</code> to system path? Is this the correct way to solve the problem?</p>
<p>The <code>cPickled</code> file looks something like</p>
<pre><code>ccopy_reg
_reconstructor
p1
(cpackageA.moduleA
ClassA
p2
c__builtin__
object
p3
NtRp4
</code></pre>
<p>The old project hierarchy is of the sort</p>
<pre><code>packageA/
__init__.py
moduleA.py
moduleB.py
packageB/
__init__.py
moduleC.py
moduleD.py
</code></pre>
<p>I'd like to put all of that into a <code>WrapperPackage</code></p>
<pre><code>MyPackage/
.. __init__.py
.. myModuleX.py
.. myModuleY.py
WrapperPackage/
.. __init__.py
.. packageA/
.. __init__.py
.. moduleA.py
.. moduleB.py
.. packageB/
.. __init__.py
.. moduleC.py
.. moduleD.py
</code></pre> | 13,398,680 | 4 | 1 | null | 2012-11-15 13:29:26.7 UTC | 10 | 2020-04-27 02:05:26.947 UTC | 2012-11-15 14:52:34.27 UTC | null | 100,190 | null | 100,190 | null | 1 | 25 | python|import|pickle | 11,802 | <p>You'll need to create an alias for the pickle import to work; the following to the <code>__init__.py</code> file of the <code>WrapperPackage</code> package:</p>
<pre><code>from .packageA import * # Ensures that all the modules have been loaded in their new locations *first*.
from . import packageA # imports WrapperPackage/packageA
import sys
sys.modules['packageA'] = packageA # creates a packageA entry in sys.modules
</code></pre>
<p>It may be that you'll need to create additional entries though:</p>
<pre><code>sys.modules['packageA.moduleA'] = moduleA
# etc.
</code></pre>
<p>Now cPickle will find <code>packageA.moduleA</code> and <code>packageA.moduleB</code> again at their old locations.</p>
<p>You may want to re-write the pickle file afterwards, the new module location will be used at that time. The additional aliases created above should ensure that the modules in question have the new location name for <code>cPickle</code> to pick up when writing the classes again.</p> |
13,774,446 | How to do a case with multiple conditions? | <p>In the 1 month experience I've had with any programming language, I've assumed that <code>switch</code> <code>case</code> conditions would accept anything in the parenthesis as a boolean checking thingamajig, ie
these:</p>
<pre><code>|| && < >
</code></pre>
<p>Know what I mean?</p>
<p>something like</p>
<pre><code>char someChar = 'w';
switch (someChar) {
case ('W' ||'w'):
System.out.println ("W or w");
}
</code></pre>
<p>Sadly, doesn't seem to work that way. I can't have boolean checking in switch case. </p>
<p>Is there a way around it?</p>
<p>By the way, terribly sorry if I'm sounding confusing. I don't quite know the names for everything in this language yet :X<br>
Any answers appreciated</p> | 13,774,469 | 5 | 5 | null | 2012-12-08 04:21:48.133 UTC | 5 | 2018-06-04 12:43:17.913 UTC | 2014-06-25 21:25:58.583 UTC | null | 2,246,344 | null | 1,786,725 | null | 1 | 26 | java|boolean|switch-statement|case | 60,193 | <p>You can achieve an OR for cases like this:</p>
<pre><code>switch (someChsr) {
case 'w':
case 'W':
// some code for 'w' or 'W'
break;
case 'x': // etc
}
</code></pre>
<p>Cases are like a "goto" and multiple gotos can share the same line to start execution.</p> |
13,665,930 | Use of ellipsis(...) in Java? | <p>I was looking through some code and saw the following notation. I'm somewhat unsure what the three dots mean and what you call them. </p>
<pre><code>void doAction(Object...o);
</code></pre>
<p>Thanks.</p> | 13,665,935 | 2 | 0 | null | 2012-12-02 02:44:17.88 UTC | 7 | 2016-03-25 18:01:28.76 UTC | 2012-12-02 09:31:53.913 UTC | null | 1,719,067 | null | 1,322,736 | null | 1 | 34 | java|oop|object|syntax | 30,534 | <p>It means that this method can receive more than one Object as a parameter. To better understating check the following example from <a href="http://today.java.net/pub/a/today/2004/04/19/varargs.html" rel="noreferrer">here</a>:</p>
<blockquote>
<p>The ellipsis (...) identifies a variable number of arguments, and is
demonstrated in the following summation method.</p>
</blockquote>
<pre><code>static int sum (int ... numbers)
{
int total = 0;
for (int i = 0; i < numbers.length; i++)
total += numbers [i];
return total;
}
</code></pre>
<blockquote>
<p>Call the summation method with as many comma-delimited integer
arguments as you desire -- within the JVM's limits. Some examples: sum
(10, 20) and sum (18, 20, 305, 4).</p>
</blockquote>
<p>This is very useful since it permits your method to became more abstract. Check also this nice <a href="https://stackoverflow.com/questions/13435714/how-to-concatenate-string-arrays-in-java">example</a> from SO, were the user takes advantage of the ... notation to make a method to concatenate string arrays in Java.</p>
<p>Another example from <a href="http://viralpatel.net/blogs/varargs-in-java-variable-argument-method-in-java-5/" rel="noreferrer">Variable argument method in Java 5</a></p>
<pre><code>public static void test(int some, String... args) {
System.out.print("\n" + some);
for(String arg: args) {
System.out.print(", " + arg);
}
}
</code></pre>
<p>As mention in the comment section: </p>
<blockquote>
<p>Also note that if the function passes other parameters of different
types than varargs parameter, the vararg parameter should be the last
parameter in the function declaration <strong>public void test (Typev ... v ,
Type1 a, Type2 b)</strong> or <strong>public void test(Type1 a, Typev ... v
recipientJids, Type2 b)</strong> - is <strong>illegal</strong>. ONLY <strong>public void test(Type1 a,
Type2 b, Typev ... v)</strong></p>
</blockquote> |
13,783,315 | Sum of list of lists; returns sum list | <p>Let <code>data = [[3,7,2],[1,4,5],[9,8,7]]</code></p>
<p>Let's say I want to sum the elements for the indices of each list in the list, like adding numbers in a matrix column to get a single list. I am assuming that all lists in data are equal in length.</p>
<pre><code> print foo(data)
[[3,7,2],
[1,4,5],
[9,8,7]]
_______
>>>[13,19,14]
</code></pre>
<p>How can I iterate over the list of lists without getting an index out of range error? Maybe lambda? Thanks!</p> | 13,783,363 | 10 | 0 | null | 2012-12-09 00:09:23.523 UTC | 15 | 2020-01-05 18:04:34.07 UTC | 2016-09-14 14:04:50.203 UTC | null | 1,945,981 | null | 1,766,730 | null | 1 | 36 | python|list|matrix|sum | 83,535 | <p>You could try this:</p>
<pre><code>In [9]: l = [[3,7,2],[1,4,5],[9,8,7]]
In [10]: [sum(i) for i in zip(*l)]
Out[10]: [13, 19, 14]
</code></pre>
<p>This uses a combination of <code>zip</code> and <code>*</code> to unpack the list and then zip the items according to their index. You then use a list comprehension to iterate through the groups of similar indices, summing them and returning in their 'original' position.</p>
<p>To hopefully make it a bit more clear, here is what happens when you iterate through <code>zip(*l)</code>:</p>
<pre><code>In [13]: for i in zip(*l):
....: print i
....:
....:
(3, 1, 9)
(7, 4, 8)
(2, 5, 7)
</code></pre>
<p>In the case of lists that are of unequal length, you can use <code>itertools.izip_longest</code> with a <code>fillvalue</code> of <code>0</code> - this basically fills missing indices with <code>0</code>, allowing you to sum all 'columns':</p>
<pre><code>In [1]: import itertools
In [2]: l = [[3,7,2],[1,4],[9,8,7,10]]
In [3]: [sum(i) for i in itertools.izip_longest(*l, fillvalue=0)]
Out[3]: [13, 19, 9, 10]
</code></pre>
<p>In this case, here is what iterating over <code>izip_longest</code> would look like:</p>
<pre><code>In [4]: for i in itertools.izip_longest(*l, fillvalue=0):
...: print i
...:
(3, 1, 9)
(7, 4, 8)
(2, 0, 7)
(0, 0, 10)
</code></pre> |
24,308,975 | How to pass a class type as a function parameter | <p>I have a generic function that calls a web service and serialize the JSON response back to an object.</p>
<pre><code>class func invokeService<T>(service: String, withParams params: Dictionary<String, String>, returningClass: AnyClass, completionHandler handler: ((T) -> ())) {
/* Construct the URL, call the service and parse the response */
}
</code></pre>
<p>What I'm trying to accomplish is is the equivalent of this Java code</p>
<pre><code>public <T> T invokeService(final String serviceURLSuffix, final Map<String, String> params,
final Class<T> classTypeToReturn) {
}
</code></pre>
<ul>
<li>Is my method signature for what I'm trying to accomplish correct?</li>
<li>More specifically, is specifying <code>AnyClass</code> as a parameter type the
right thing to do?</li>
<li>When calling the method, I'm passing <code>MyObject.self</code> as the returningClass value, but I get a compilation <strong>error "Cannot convert the expression's type '()' to type 'String'"</strong></li>
</ul>
<pre><code>CastDAO.invokeService("test", withParams: ["test" : "test"], returningClass: CityInfo.self) { cityInfo in /*...*/
}
</code></pre>
<hr>
<p><strong>Edit:</strong> </p>
<p>I tried using <code>object_getClass</code>, as mentioned by holex, but now I get:</p>
<blockquote>
<p>error: "Type 'CityInfo.Type' does not conform to protocol 'AnyObject'"</p>
</blockquote>
<p>What need to be done to conform to the protocol?</p>
<pre><code>class CityInfo : NSObject {
var cityName: String?
var regionCode: String?
var regionName: String?
}
</code></pre> | 24,735,880 | 7 | 2 | null | 2014-06-19 14:24:21.277 UTC | 35 | 2022-07-15 16:37:00.987 UTC | 2018-04-06 14:37:29.35 UTC | null | 5,175,709 | null | 1,552,714 | null | 1 | 165 | swift|generics|type-inference | 116,177 | <p>You are approaching it in the wrong way: in Swift, unlike Objective-C, classes have specific types and even have an inheritance hierarchy (that is, if class <code>B</code> inherits from <code>A</code>, then <code>B.Type</code> also inherits from <code>A.Type</code>):</p>
<pre><code>class A {}
class B: A {}
class C {}
// B inherits from A
let object: A = B()
// B.Type also inherits from A.Type
let type: A.Type = B.self
// Error: 'C' is not a subtype of 'A'
let type2: A.Type = C.self
</code></pre>
<p>That's why you shouldn't use <code>AnyClass</code>, unless you really want to allow <em>any</em> class. In this case the right type would be <code>T.Type</code>, because it expresses the link between the <code>returningClass</code> parameter and the parameter of the closure.</p>
<p>In fact, using it instead of <code>AnyClass</code> allows the compiler to correctly infer the types in the method call:</p>
<pre><code>class func invokeService<T>(service: String, withParams params: Dictionary<String, String>, returningClass: T.Type, completionHandler handler: ((T) -> ())) {
// The compiler correctly infers that T is the class of the instances of returningClass
handler(returningClass())
}
</code></pre>
<p>Now there's the problem of constructing an instance of <code>T</code> to pass to <code>handler</code>: if you try and run the code right now the compiler will complain that <code>T</code> is not constructible with <code>()</code>. And rightfully so: <code>T</code> has to be explicitly constrained to require that it implements a specific initializer.</p>
<p>This can be done with a protocol like the following one:</p>
<pre><code>protocol Initable {
init()
}
class CityInfo : NSObject, Initable {
var cityName: String?
var regionCode: String?
var regionName: String?
// Nothing to change here, CityInfo already implements init()
}
</code></pre>
<p>Then you only have to change the generic constraints of <code>invokeService</code> from <code><T></code> to <code><T: Initable></code>.</p>
<h2>Tip</h2>
<p>If you get strange errors like "Cannot convert the expression's type '()' to type 'String'", it is often useful to move every argument of the method call to its own variable. It helps narrowing down the code that is causing the error and uncovering type inference issues:</p>
<pre><code>let service = "test"
let params = ["test" : "test"]
let returningClass = CityInfo.self
CastDAO.invokeService(service, withParams: params, returningClass: returningClass) { cityInfo in /*...*/
}
</code></pre>
<p>Now there are two possibilities: the error moves to one of the variables (which means that the wrong part is there) or you get a cryptic message like "Cannot convert the expression's type <code>()</code> to type <code>($T6) -> ($T6) -> $T5</code>".</p>
<p>The cause of the latter error is that the compiler is not able to infer the types of what you wrote. In this case the problem is that <code>T</code> is only used in the parameter of the closure and the closure you passed doesn't indicate any particular type so the compiler doesn't know what type to infer. By changing the type of <code>returningClass</code> to include <code>T</code> you give the compiler a way to determine the generic parameter.</p> |
3,656,391 | What's the dSYM and how to use it? (iOS SDK) | <p>Sometimes the compiler produces .dSYM files. I guess this is a debugging related file, but I don't know what it is, and how to use it.</p>
<p>What is a .dSYM? How do I use it?</p> | 23,854,688 | 2 | 1 | null | 2010-09-07 06:57:57.217 UTC | 37 | 2021-04-27 00:01:34.03 UTC | 2017-09-10 06:11:58.26 UTC | null | 1,033,581 | null | 246,776 | null | 1 | 148 | debugging|sdk|compilation|ios | 114,478 | <p>dSYM files store the debug symbols for your app</p>
<p>Services like Crashlytics use it to replace the symbols in the crash logs with the appropriate methods names so it will be readable and will make sense.</p>
<p>The benefit of using the dSYM is that you don't need to ship your App with its symbols making it harder to reverse engineer it and also reduce your binary size</p>
<p>In order to use to symbolicate the crash log you need to drag the crash log into the device's device logs in the organizer of the machine that compiled the app binary (a machine that stores the dSYM)</p>
<p>If you have the dSYM but don't have the machine the compiled the app binary follow the instructions in <a href="http://noverse.com/blog/2010/03/how-to-deal-with-an-iphone-crash-report/" rel="noreferrer">this</a> link in order to install the dSYM into the machine.</p>
<p>There is a <a href="https://github.com/inket/MacSymbolicator" rel="noreferrer">mac app</a> that helps you symbolicate a crash log in case you need to do it yourself.</p>
<p>For more information please see <a href="https://developer.apple.com/library/content/technotes/tn2151/_index.html" rel="noreferrer">apple technical note TN2151</a></p> |
29,785,320 | Mystery console error with IOHIDFamily | <p>For one of my projects, this error message in Xcode's console happens every time I run a build in the iOS Simulator. It's been happening for over a year and I thought it would eventually go away with an update to Xcode. I've dereferenced and relinked all the Frameworks and I am not explicitly calling anything from the IOHIDFamily, whatever that is! It doesn't seem to affect my program execution but I would really like to figure out why it dumps all this every time.</p>
<pre><code>2015-04-21 18:20:13.997 Vector-Z_beta[12370:1453236] Error loading /System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib: dlopen(/System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib, 262): no suitable image found. Did find:
/System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib: mach-o, but not built for iOS simulator
2015-04-21 18:20:13.997 Vector-Z_beta[12370:1453236] Cannot find function pointer IOHIDLibFactory for factory 13AA9C44-6F1B-11D4-907C-0005028F18D5 in CFBundle/CFPlugIn 0x78da9a80 </System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin> (bundle, not loaded)
2015-04-21 18:20:13.997 Vector-Z_beta[12370:1453236] Error loading /System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib: dlopen(/System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib, 262): no suitable image found. Did find:
/System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib: mach-o, but not built for iOS simulator
2015-04-21 18:20:13.997 Vector-Z_beta[12370:1453236] Cannot find function pointer IOHIDLibFactory for factory 13AA9C44-6F1B-11D4-907C-0005028F18D5 in CFBundle/CFPlugIn 0x78da9a80 </System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin> (bundle, not loaded)
2015-04-21 18:20:13.998 Vector-Z_beta[12370:1453236] Error loading /System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib: dlopen(/System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib, 262): no suitable image found. Did find:
/System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib: mach-o, but not built for iOS simulator
2015-04-21 18:20:13.998 Vector-Z_beta[12370:1453236] Cannot find function pointer IOHIDLibFactory for factory 13AA9C44-6F1B-11D4-907C-0005028F18D5 in CFBundle/CFPlugIn 0x78da9a80 </System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin> (bundle, not loaded)
2015-04-21 18:20:13.998 Vector-Z_beta[12370:1453236] Error loading /System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib: dlopen(/System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib, 262): no suitable image found. Did find:
/System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib: mach-o, but not built for iOS simulator
2015-04-21 18:20:13.998 Vector-Z_beta[12370:1453236] Cannot find function pointer IOHIDLibFactory for factory 13AA9C44-6F1B-11D4-907C-0005028F18D5 in CFBundle/CFPlugIn 0x78da9a80 </System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin> (bundle, not loaded)
</code></pre> | 33,970,257 | 6 | 5 | null | 2015-04-22 00:01:33.787 UTC | 16 | 2015-12-10 09:27:21.847 UTC | 2015-04-22 00:19:32.103 UTC | null | 608,639 | null | 326,398 | null | 1 | 55 | ios|objective-c|xcode | 12,550 | <p>When deploying to a real iOS device you are building for an ARM architecture, when deploying to the iOS simulator you are building for an x386 architecture.</p>
<p>In the latter case your app links with mach-o files present on your Mac (unless as someone suggested you only link with SDK assemblies, not native Mac ones, but this will really slow down your build and isn’t an available option anymore in recent Xcode versions I believe). </p>
<p>Apparently, one of these mach-o files - the IOHIDFamily extension one, which seems to be linked if GameKit.framework is linked as a library - is not specifically built for the iOS simulator. Hence, the message.
As I understand this is a confirmed Apple bug and will be fixed by Apple at some point.</p>
<p>It is an issue with the iOS simulator only and can be safely ignored.</p> |
16,087,341 | Multiple dex files - Conversion to Dalvik format failed - Unable to execute dex | <p>I have 2 app versions - pro and lite. They are both already on the market at v1.01. I am trying to release v1.1 for both. This update includes SwawrmConnect integration in order to use their global leaderboards.</p>
<p>I should start off by saying I know I am not maintaining my code correctly. I have 2 completely separate apps and that share probably 90% of their code. I maintain them separately because after a week or 2 or 3 of failing to figure out how to do a library and share code, I gave up and just went this way with it.</p>
<p>SwarmConnect is the first jar I have used and had to make a library to two apps (see screenshot of file structure below).</p>
<p>Right now my lite version is working and is ready for release. I am now trying to get my pro version to where it needs to be for release. I am fairly certain all java/xml files are up to date and ready. When I went to run the pro version in the emulator, I get the below error:</p>
<pre><code>[2013-04-18 11:24:41 - Dex Loader] Unable to execute dex: Multiple dex files define Lcom/swarmconnect/loopj/android/http/AsyncHttpResponseHandler;
[2013-04-18 11:24:41 - BibleTriviaPro] Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Lcom/swarmconnect/loopj/android/http/AsyncHttpResponseHandler;
</code></pre>
<p>Things I've tried:</p>
<ul>
<li>Clean/rebuild</li>
<li>Update Eclipse</li>
<li>Delete bin and gen folders</li>
<li>Restart Eclipse</li>
<li>Plus some other stuff</li>
</ul>
<p>My file structure:</p>
<p><img src="https://i.stack.imgur.com/4zHBk.png" alt="enter image description here"></p>
<p>Could the problem be is I am trying to use SwarmConnect as a library for 2 projects (lite and pro)?</p>
<p>EDIT:</p>
<p>Below is the file structure for the lite version that is working perfectly. Compiles and runs on emulator.</p>
<p><img src="https://i.stack.imgur.com/7fD14.png" alt="enter image description here"></p> | 16,088,209 | 5 | 11 | null | 2013-04-18 15:39:54.01 UTC | 2 | 2015-02-05 13:22:47.67 UTC | 2013-04-18 15:48:22.113 UTC | null | 1,866,707 | null | 1,866,707 | null | 1 | 18 | java|android|dalvik|dex | 38,231 | <p>Coincidentally I ran into the same issue just day before yesterday. Here's what I suggest you to do.</p>
<p>First and foremost make sure that you have a backup of all the jars presently residing in the 'Android Dependencies'/'libs' folder.</p>
<p>Now, lets fix the lite version first by following these steps. </p>
<ol>
<li><p>Remove all <code>jar</code> files except <code>android-support-v4.jar</code> from the 'Android Dependencies' folder under Project Explorer in Eclipse.</p></li>
<li><p>Similarly remove all Jar files except <code>android-support-v4.jar</code> from the <code>libs</code> folder under Project Explorer in Eclipse.</p></li>
<li><p>Now Right click on your project-> Select Properties-> Select Java Build Path-> Select Add External JARs. Add all the necessary <code>jar</code> files (just make sure you add a particular <code>jar</code> file only once). </p></li>
</ol>
<p>Finally clean the project and build it. Now apply the same sequence of steps to the pro version.
That should do it.</p>
<p>UPDATE:- In case you see Eclipse cribbing about some compile time errors after doing all this all you might have to do is to just fix those compile time errors by doing the necessary imports by pressing <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>O</kbd>.</p>
<p>[I assume that there's no linkage between the pro and lite versions of the project in terms of source dependencies etc.. what I mean to say basically they are totally independent.]</p>
<p>Hope this helps.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.