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
20,746,745
Adding scroll bar to dynamic ul li
<p>I searched through many posts and forum as i thought this might be a basic stuff but didnot find it so asking here,All i am trying to do is add scroll bar if the height is more than certain limit lets say if menu items are more than 3.</p> <p>I have created a jsfiddle <a href="http://jsfiddle.net/euSWB/" rel="noreferrer">http://jsfiddle.net/euSWB/</a></p> <p>If you are not able to access it then here is the HTML and CSS HTML</p> <pre><code>&lt;ul id="mnav"&gt; &lt;li&gt;&lt;a&gt;&lt;b&gt;Home&lt;/b&gt;&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a&gt;&lt;b&gt;SQL Server vs Oracle&lt;/b&gt;&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a&gt;Basic SQL : Declare variables and assign values&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a&gt;Basic SQL : Inner Join, Outer Join and Cross Join&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a&gt;Basic SQL : Padding and Trimming&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a&gt;Basic SQL : Union,Except/Minus,Intersect&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a style="border-bottom-color: currentColor; border-bottom-width: 0px; border-bottom-style: none;"&gt;Update from Select&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;&lt;b&gt;SSIS&lt;/b&gt;&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a&gt;Coalesce in SSIS&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a &gt;Universal CSV Generator&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a &gt;Parsing a row into multiple in CSV&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a style="border-bottom-color: currentColor; border-bottom-width: 0px; border-bottom-style: none;" &gt;XML Task in SSIS&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt;&lt;/ul&gt; </code></pre> <p>CSS</p> <pre><code>#mnav { margin-left: -30px; margin-right: -30px; } #mnav li { float: left; list-style: none; } #mnav li a, #mnav li a:link, #mnav li a:visited { text-decoration: none; } #mnav li a:hover, #mnav li a:active { text-decoration: none; } #mnav li:hover, #mnav li.sfhover { position: static; } #mnav li ul { display: block; z-index: 9999; position: absolute; left: -999em; width: 400px; margin: 0px; border: 1px solid #ddd; } #mnav li:hover ul, #mnav li.sfhover ul { left: auto; } #mnav li ul li a, #mnav li ul li a:link, #mnav li ul li a:visited { display: block; margin: 0; text-decoration: none; z-index: 9999; border-bottom: 1px dotted #ccc; width: 500px; } #mnav li ul li a:hover, #mnav li ul li a:active { display: block; margin: 0; text-decoration: none; } </code></pre>
20,793,417
3
0
null
2013-12-23 15:45:55.227 UTC
2
2013-12-27 01:15:39.077 UTC
null
null
null
null
3,006,187
null
1
8
javascript|html|css
46,989
<p>I've made a couple of adjustments to your original stylesheet, and now it will show the scroll bar, but only when it exceeds the height of 3 list items (63 pixels in this case). Here's the final CSS code: </p> <pre><code>#mnav { margin-left: -30px; margin-right: -30px; } #mnav li { float: left; list-style: none; margin:0 10px;/*Keeping 10px space between each nav element*/ } #mnav li a,/*These can all be merged into a single style*/ #mnav li a:link, #mnav li a:visited, #mnav li a:hover, #mnav li a:active { text-decoration: none; } #mnav li ul { display: none;/*This is the default state.*/ z-index: 9999; position: absolute; width: 400px; max-height:63px;/*The important part*/ overflow-y:auto;/*Also...*/ overflow-x:hidden;/*And the end of the important part*/ margin: 0px; padding-left:5px;/*Removing the large whitespace to the left of list items*/ border: 1px solid #ddd; } #mnav li:hover ul, #mnav li.sfhover ul { display:block;/*This is the hovered state*/ } #mnav li ul li a, #mnav li ul li a:link, #mnav li ul li a:visited { display: block; margin: 0; text-decoration: none; z-index: 9999; border-bottom: 1px dotted #ccc; width:400px; } #mnav li ul li a:hover, #mnav li ul li a:active { display: block; margin: 0; text-decoration: none; } </code></pre> <p><strong><a href="http://jsfiddle.net/euSWB/18/">Here's the demo of it</a></strong>. I've also, for demonstration purposes, inserted 2 extra <code>&lt;li&gt;</code> elements to the <strong>Home</strong> and <strong>SQL Server vs Oracle</strong> items. The <strong>Home</strong> item will show how the popup behaves if there are fewer than 3 list items there.</p> <p>To explain each of the changed bits, first the code that actually does the trick:</p> <ul> <li>defining the <code>max-height</code> to 63 will make the ul behave normally if it stays under 63px high, but if it exceeds that, it will overflow and show a scroll bar. If you want to show more items, just increase the <code>max-height</code> to the desired height. Currently the height of each item is 21px, so I used that to get the 63px for 3 items.</li> <li>Since the overflow should only show a scroll bar for the vertical direction, only <code>overflow-y:auto;</code> should be there, and <code>overflow-x:hidden</code> to prevent a scrollbar in the horizontal direction.</li> </ul> <p>And then the other general changes I made:</p> <ul> <li>I've added 20px margin between items (10px on either side of the element) to make the list look a bit better here. You may want to apply your own style though, this is just for this demo.</li> <li>I've changed your hiding technique from 'shoving it off to <code>-999em</code> to the left' to hiding it via <code>display:none</code>. This is better to work with, since elements that are <code>display:none</code> will not render in search engines, so this will help in those situations. In general I think hiding things with <code>display:none</code> is just better than shoving it off the screen, while it's still actually there</li> <li>I've removed the padding to the left of the <code>ul</code> since it just looked quite bad. No need for the default padding if you're not using it for a dotted/numbered list.</li> </ul> <p>This should also work considering your comment to <em>Zachary Carter</em>'s answer, since this won't show a huge white box if you define the <code>max-height</code> to 210px (10 items).</p>
42,637,099
Difference between the == and %in% operators in R
<p>My question concerns the practical difference between the <code>==</code> and <code>%in%</code> operators in R.</p> <p>I have run into an instance at work where filtering with either operator gives different results (e.g. one results on 800 rows, and the other 1200). I have run into this problem in the past and am able to validate in a way that ensures I get the results I desire. However, I am still stumped regarding how they are different.</p> <p>Can someone please shed some light on how these operators are different? </p>
42,637,186
4
1
null
2017-03-06 22:52:56.443 UTC
18
2017-10-04 09:28:17.833 UTC
2017-10-04 09:28:17.833 UTC
null
680,068
null
6,608,950
null
1
23
r|operators|filtering
91,259
<p><code>%in%</code> is <strong>value matching</strong> and "returns a vector of the positions of (first) matches of its first argument in its second" (See <code>help('%in%')</code>) This means you could compare vectors of different lengths to see if elements of one vector match at least one element in another. The length of output will be equal to the length of the vector being compared (the first one).</p> <pre><code>1:2 %in% rep(1:2,5) #[1] TRUE TRUE rep(1:2,5) %in% 1:2 #[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE #Note this output is longer in second </code></pre> <hr> <p><code>==</code> is <strong>logical operator</strong> meant to compare if two things are exactly equal. If the vectors are of equal length, elements will be compared element-wise. If not, vectors will be recycled. The length of output will be equal to the length of the longer vector.</p> <pre><code>1:2 == rep(1:2,5) #[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE rep(1:2,5) == 1:2 #[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE </code></pre> <hr> <pre><code>1:10 %in% 3:7 #[1] FALSE FALSE TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE #is same as sapply(1:10, function(a) any(a == 3:7)) #[1] FALSE FALSE TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE </code></pre> <hr> <p>NOTE: If possible, try to use <code>identical</code> or <code>all.equal</code> instead of <code>==</code> and.</p>
36,184,795
How to get enum from raw value in Swift?
<p>I'm trying to get enum type from raw value:</p> <pre><code>enum TestEnum: String { case Name case Gender case Birth var rawValue: String { switch self { case .Name: return "Name" case .Gender: return "Gender" case .Birth: return "Birth Day" } } } let name = TestEnum(rawValue: "Name") //Name let gender = TestEnum(rawValue: "Gender") //Gender </code></pre> <p>But it seems that <code>rawValue</code> doesn't work for string with spaces:</p> <pre><code>let birth = TestEnum(rawValue: "Birth Day") //nil </code></pre> <p>Any suggestions how to get it?</p>
36,184,998
8
1
null
2016-03-23 17:24:26.937 UTC
12
2021-12-03 12:39:23.54 UTC
null
null
null
null
1,136,218
null
1
90
ios|swift|enums
86,921
<p>Too complicated, just assign the raw values directly to the cases</p> <pre><code>enum TestEnum: String { case Name = "Name" case Gender = "Gender" case Birth = "Birth Day" } let name = TestEnum(rawValue: "Name")! //Name let gender = TestEnum(rawValue: "Gender")! //Gender let birth = TestEnum(rawValue: "Birth Day")! //Birth </code></pre> <p>If the case name matches the raw value you can even omit it</p> <pre><code>enum TestEnum: String { case Name, Gender, Birth = "Birth Day" } </code></pre> <p>In Swift 3+ all enum cases are <code>lowercased</code></p>
19,934,703
How to use javascript to set attribute of selected web element using selenium Webdriver using java?
<p>I want to use javascript to set attribute for selected element on webpage.</p> <p>I have found 2 ways to set attribute using javascript</p> <p>1</p> <pre><code> WebDriver driver; // Assigned elsewhere JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("document.getElementByID('//id of element').setAttribute('attr', '10')"); </code></pre> <p>2</p> <pre><code>WebElement element = driver.findElement(By.id("foo")); String contents = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].innerHTML;", element); </code></pre> <p>But I want to apply javascript to specific webelement which i have found using selenium webdriver</p> <p>as an example i have select one link using selenium webdriver</p> <pre><code>driver.findElement(By.linkText("Click ME")) </code></pre> <p>Now I want to set attribute of this webelement using javascript </p> <p>but I don't know how to combine both</p> <p>please help me to find solution</p>
19,934,852
3
0
null
2013-11-12 16:34:46.437 UTC
5
2020-09-04 10:38:52.34 UTC
null
null
null
null
1,015,801
null
1
15
java|javascript|selenium|selenium-webdriver
40,881
<p>Along the lines of:</p> <pre><code>JavascriptExecutor js = (JavascriptExecutor) driver; WebElement element = driver.findElement(By.linkText("Click ME")); js.executeScript("arguments[0].setAttribute('attr', '10')",element); </code></pre>
5,903,281
@property/@synthesize question
<p>I'm going through all of my documentation regarding memory management and I'm a bit confused about something.</p> <p>When you use @property, it creates getters/setters for the object:</p> <p>.h: @property (retain, nonatomic) NSString *myString</p> <p>.m: @synthesize myString</p> <p>I understand that, but where I get confused is the use of self. I see different syntax in different blogs and books. I've seen:</p> <pre><code>myString = [NSString alloc] initWithString:@"Hi there"]; </code></pre> <p>or </p> <pre><code>self.myString = [NSString alloc] initWithString:@"Hi there"]; </code></pre> <p>Then in dealloc I see:</p> <pre><code>self.myString = nil; </code></pre> <p>or </p> <pre><code>[myString release]; </code></pre> <p>or </p> <pre><code>self.myString = nil; [myString release]; </code></pre> <p>On this site, someone stated that using self adds another increment to the retain count? Is that true, I haven't seen that anywhere. </p> <p>Do the automatic getters/setters that are provided autorelease? </p> <p>Which is the correct way of doing all of this? </p> <p>Thanks!</p>
5,903,354
3
0
null
2011-05-05 19:46:20.513 UTC
11
2011-05-10 21:58:37.39 UTC
2011-05-08 08:44:03.467 UTC
null
296,387
null
571,905
null
1
10
iphone|objective-c|memory-management|properties|synthesizer
630
<p>If you are not using the dot syntax you are not using any setter or getter.</p> <p>The next thing is, it depends on how the property has been declared.</p> <p>Let's assume something like this:</p> <pre><code>@property (nonatomic, retain) Article *article; ... @synthesize article; </code></pre> <p><strong>Assigning</strong> something to article with </p> <pre><code>self.article = [[Article alloc] init]; </code></pre> <p>will overretain the instance given back by alloc/init and cause a leak. This is because the setter of article will retain it and will release any previous instance for you.</p> <p>So you could rewrite it as:</p> <pre><code>self.article = [[[Article alloc] init] autorelease]; </code></pre> <p>Doing this</p> <pre><code>article = [[Article alloc] init]; </code></pre> <p>is also ok, but could involve a leak as article may hold a reference to an instance already. So freeing the value beforehand would be needed:</p> <pre><code>[article release]; article = [[Article alloc] init]; </code></pre> <hr> <p><strong>Freeing memory</strong> could be done with</p> <pre><code>[article release]; </code></pre> <p>or with</p> <pre><code>self.article = nil; </code></pre> <p>The first one does access the field directly, no setters/getters involved. The second one sets nil to the field by using a setter. Which will release the current instance, if there is one before setting it to nil.</p> <p><strong>This construct</strong></p> <pre><code>self.myString = nil; [myString release]; </code></pre> <p>is just too much, it actually sends release to nil, which is harmless but also needless.</p> <p><strong>You just have to mentally map hat using the dot syntax is using accessor methods:</strong></p> <pre><code>self.article = newArticle // is [self setArticle:newArticle]; </code></pre> <p>and</p> <pre><code>myArticle = self.article; // is myArticle = [self article]; </code></pre> <hr> <p><em>Some suggestions on reading, all official documents by Apple:</em></p> <p><strong>The Objective-C Programming Language</strong></p> <ul> <li><a href="http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocObjectsClasses.html#//apple_ref/doc/uid/TP30001163-CH11-SW17" rel="nofollow">Dot Syntax</a></li> <li><a href="http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW1" rel="nofollow">Declared Properties</a></li> </ul> <p><strong>Memory Management Programming Guide</strong></p> <ul> <li><a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmObjectOwnership.html#//apple_ref/doc/uid/20000043-BEHDEDDB" rel="nofollow">Object Ownership and Disposal</a></li> <li><a href="http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html#//apple_ref/doc/uid/TP40004447-SW4" rel="nofollow">Using Accessor Methods</a></li> </ul>
5,686,692
Storing binary objects in Neo4j
<p>Neo4j doesn't seem to allow me to store binary objects. Does this mean I must used Neo4j in conjuntion with another data store, such as the filesystem., Oracle, etc?</p>
5,708,108
4
0
null
2011-04-16 13:04:35.367 UTC
9
2014-04-11 14:45:10.693 UTC
null
null
null
null
190,822
null
1
13
neo4j
8,403
<p>Daniel already answered that it's possible to store binary objects in Neo4J. </p> <p>But i would suggest you not to do so. You can do nothing interesting with binary objects in database. You cannot search them. The only thing you will achieve by storing binary objects - grow the file size of your database. Mind you, Neo4J is not scalable horizontally. It does not have automatic sharding. So if your db grows too big, you are in trouble. By storing binaries in a file system or external distributed key-value store like riak, cassandra, hadoop etc, you are keeping your database small, which is good for performance, backups and avoiding horizontal scaling problems.</p>
5,846,637
Why an inline "background-image" style doesn't work in Chrome 10 and Internet Explorer 8?
<p>Why the <a href="http://jsfiddle.net/dvqU8/13/" rel="noreferrer">following example</a> shows the image in Firefox 4, but not in Chrome 10 and Internet Explorer 8?</p> <p>HTML:</p> <pre><code>&lt;div style="background-image: url('http://www.mypicx.com/uploadimg/1312875436_05012011_2.png')"&gt;&lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>div { width: 60px; height: 60px; border: 1px solid black; } </code></pre> <p>Any ideas for workarounds?</p>
5,847,075
4
3
null
2011-05-01 05:19:30.953 UTC
9
2020-10-07 03:41:44.583 UTC
2018-06-20 14:46:47.73 UTC
null
107,625
null
247,243
null
1
58
html|css|google-chrome|internet-explorer-8|background-image
360,089
<p>As c-smile mentioned: Just need to remove the apostrophes in the <code>url()</code>:</p> <pre><code>&lt;div style="background-image: url(http://i54.tinypic.com/4zuxif.jpg)"&gt;&lt;/div&gt; </code></pre> <p><a href="http://jsfiddle.net/dvqU8/18/" rel="noreferrer">Demo here</a></p>
34,838,542
How to get Timezone offset from moment Object?
<p>I have <code>moment</code> Object defined as:</p> <pre><code>var moment = require('moment'); moment('2015-12-20T12:00:00+02:00'); </code></pre> <p>When I print it, I get:</p> <pre><code>_d: Sun Dec 20 2015 12:00:00 GMT+0200 (EET) _f: "YYYY-MM-DDTHH:mm:ssZ" _i: "2015-12-20T12:00:00+02:00" _isAMomentObject: true _isUTC: false _locale: r _pf: Object _tzm: 120 </code></pre> <p>How to fetch by right way <code>_tzm</code>? (suppose its offset in minutes)</p> <p>Thanks,</p>
34,838,576
1
2
null
2016-01-17 12:54:37.427 UTC
1
2016-01-17 13:03:59.013 UTC
null
null
null
null
3,021,358
null
1
22
javascript|node.js|momentjs
49,415
<p>Just access the property like you would in any object</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var result = moment('2015-12-20T12:00:00+02:00'); document.body.innerHTML = result._tzm;</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>Another option would be to parse the date and get the zone</p> <pre><code>moment.parseZone('2015-12-20T12:00:00+02:00').utcOffset(); // 120 // or moment().utcOffset('2015-12-20T12:00:00+02:00')._offset; // 120 </code></pre>
34,569,750
Get pixel value from CVPixelBufferRef in Swift
<p>How can I get the RGB (or any other format) pixel value from a CVPixelBufferRef? Ive tried many approaches but no success yet.</p> <pre><code>func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) { let pixelBuffer: CVPixelBufferRef = CMSampleBufferGetImageBuffer(sampleBuffer)! CVPixelBufferLockBaseAddress(pixelBuffer, 0) let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer) //Get individual pixel values here CVPixelBufferUnlockBaseAddress(pixelBuffer, 0) } </code></pre>
34,570,127
4
2
null
2016-01-02 19:21:30.01 UTC
9
2020-12-27 20:24:31.83 UTC
2019-10-18 12:57:06.73 UTC
null
716,682
null
791,248
null
1
18
ios|swift|image-processing|cvpixelbuffer
19,508
<p><code>baseAddress</code> is an unsafe mutable pointer or more precisely a <code>UnsafeMutablePointer&lt;Void&gt;</code>. You can easily access the memory once you have converted the pointer away from <code>Void</code> to a more specific type:</p> <pre><code>// Convert the base address to a safe pointer of the appropriate type let byteBuffer = UnsafeMutablePointer&lt;UInt8&gt;(baseAddress) // read the data (returns value of type UInt8) let firstByte = byteBuffer[0] // write data byteBuffer[3] = 90 </code></pre> <p>Make sure you use the correct type (8, 16 or 32 bit unsigned int). It depends on the video format. Most likely it's 8 bit.</p> <p><strong>Update on buffer formats:</strong></p> <p>You can specify the format when you initialize the <code>AVCaptureVideoDataOutput</code> instance. You basically have the choice of:</p> <ul> <li>BGRA: a single plane where the blue, green, red and alpha values are stored in a 32 bit integer each</li> <li>420YpCbCr8BiPlanarFullRange: Two planes, the first containing a byte for each pixel with the Y (luma) value, the second containing the Cb and Cr (chroma) values for groups of pixels</li> <li>420YpCbCr8BiPlanarVideoRange: The same as 420YpCbCr8BiPlanarFullRange but the Y values are restricted to the range 16 – 235 (for historical reasons)</li> </ul> <p>If you're interested in the color values and speed (or rather maximum frame rate) is not an issue, then go for the simpler BGRA format. Otherwise take one of the more efficient native video formats.</p> <p>If you have two planes, you must get the base address of the desired plane (see video format example):</p> <p><strong>Video format example</strong></p> <pre><code>let pixelBuffer: CVPixelBufferRef = CMSampleBufferGetImageBuffer(sampleBuffer)! CVPixelBufferLockBaseAddress(pixelBuffer, 0) let baseAddress = CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0) let bytesPerRow = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 0) let byteBuffer = UnsafeMutablePointer&lt;UInt8&gt;(baseAddress) // Get luma value for pixel (43, 17) let luma = byteBuffer[17 * bytesPerRow + 43] CVPixelBufferUnlockBaseAddress(pixelBuffer, 0) </code></pre> <p><strong>BGRA example</strong></p> <pre><code>let pixelBuffer: CVPixelBufferRef = CMSampleBufferGetImageBuffer(sampleBuffer)! CVPixelBufferLockBaseAddress(pixelBuffer, 0) let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer) let int32PerRow = CVPixelBufferGetBytesPerRow(pixelBuffer) let int32Buffer = UnsafeMutablePointer&lt;UInt32&gt;(baseAddress) // Get BGRA value for pixel (43, 17) let luma = int32Buffer[17 * int32PerRow + 43] CVPixelBufferUnlockBaseAddress(pixelBuffer, 0) </code></pre>
34,522,708
cocoapods installation stuck on "Updating local specs repositories"
<p>Any help please I have been waiting so long for this and it didn't show me any improvement.Still stucking at <code>Updating local specs repositories</code></p> <p>Actually i was trying to update pod files of library that I use on my xcode.I close it yesterday because it takes too long.And today i run again,doing <code>control + c</code> and run <code>pod install</code> again.</p> <p>It didn't work,stucking at <code>Updating local specs repositories</code></p> <p>When I open my Xcode,many errors occur because of pod issue..</p> <p>Please I need help!</p>
34,558,169
4
2
null
2015-12-30 03:58:53.14 UTC
9
2021-04-29 13:26:58.593 UTC
null
null
null
null
3,378,606
null
1
37
xcode|cocoapods
19,775
<p>There's an known error with <a href="http://blog.cocoapods.org/Repairing-Our-Broken-Specs-Repository/">http://blog.cocoapods.org/Repairing-Our-Broken-Specs-Repository/</a></p> <p>You can try to fix it by doing:</p> <pre><code>pod repo remove master pod setup pod install </code></pre>
1,895,462
GitHub and Visual Studio
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/507343/using-git-with-visual-studio">Using Git with Visual Studio</a> </p> </blockquote> <p>What's the most painless way for the Visual Studio developer to start using GitHub? Ideally the answer would involve a Visual Studio plugin, or some other integration app?</p> <ul> <li>What solutions are available today to view/update GitHub repositories? </li> <li>Can you rely or expect the same functionality as compared to other VS integrated source control plugins? </li> <li>What processes would you change, as a user, when approaching this use-case from the TFS or <a href="http://www.sourcegear.com/vault/" rel="nofollow noreferrer">SourceGear Vault</a> scenarios?</li> <li>The current use case is in single-developer mode, but certainly this question is open to single dev and teams of any size. </li> <li>Any tools that are Visual Studio plug-ins would be considered 'top of the list'</li> </ul>
2,252,205
2
2
null
2009-12-13 03:19:54.03 UTC
7
2012-12-21 12:20:39.737 UTC
2017-05-23 10:29:47.577 UTC
null
-1
null
23,199
null
1
49
visual-studio|version-control|github
32,838
<p>See <a href="https://stackoverflow.com/questions/507343/using-git-with-visual-studio">this question</a> for general hints using git with Visual Studio.</p> <p>The accepted answer was the <a href="http://sourceforge.net/projects/gitextensions" rel="nofollow noreferrer">Git Extensions</a> project.</p> <p>I'm not aware that github would require any specific extras beyond that.</p>
66,267,454
JDK is installed on mac but i'm getting "The operation couldn’t be completed. Unable to locate a Java Runtime that supports apt." sudo apt update
<p>I'm trying to run the command <code>sudo apt update</code> on my terminal in MacOS</p> <p>I'm getting this message in response: <code>The operation couldn’t be completed. Unable to locate a Java Runtime that supports apt. Please visit http://www.java.com for information on installing Java.</code></p> <p>I saw a similar question <a href="https://stackoverflow.com/questions/44009058/even-though-jre-8-is-installed-on-my-mac-no-java-runtime-present-requesting-t">here</a>, however even though I made sure to install the JDK like the solution suggested I'm still getting the same response.</p> <p>I also tried pasting</p> <pre><code>export PATH=&quot;$HOME/.jenv/bin:$PATH&quot; eval &quot;$(jenv init -)&quot; export JAVA_HOME=&quot;$HOME/.jenv/versions/`jenv version-name`&quot; </code></pre> <p>Into my .zshrc.save folder and had no luck.</p> <p>When I run <code>java -version</code> in the terminal this is what I get back:</p> <pre><code>java version &quot;15.0.2&quot; 2021-01-19 Java(TM) SE Runtime Environment (build 15.0.2+7-27) Java HotSpot(TM) 64-Bit Server VM (build 15.0.2+7-27, mixed mode, sharing) </code></pre>
66,267,603
3
2
null
2021-02-18 20:09:08.337 UTC
4
2022-06-28 10:38:00.203 UTC
2021-08-29 11:57:47.247 UTC
null
1,543,885
null
9,781,768
null
1
19
java|terminal|apt
51,046
<p>20 years ago, java shipped with a tool called <code>apt</code>: Annotation Processor Tool. This tool was obsolete not much later.</p> <p>What that update-node-js-version is talking about, is <strong>a completely and totally unrelated tool</strong>: It's the <code>Advanced Package Tool</code>, which is a tool to manage installations <strong>on debian and ubuntu</strong> - linux distros. You do not <strong>want</strong> to run this on a mac, and the instructions you found are therefore completely useless: That is how to update node-js on linux. Your machine isn't linux.</p> <p>Search around for answers involving <code>brew</code>, which is the go-to equivalent of <code>apt</code> on mac. And completely forget about java - this has NOTHING to do with java - that was just a pure coincidence.</p>
32,208,535
Laravel testing, get JSON content
<p>In Laravel's unit test, I can test a JSON API like that:</p> <pre><code>$this-&gt;post('/user', ['name' =&gt; 'Sally']) -&gt;seeJson([ 'created' =&gt; true, ]); </code></pre> <p>But what if I want to use the response. How can I get the JSON response (as an array) using <code>$this-&gt;post()</code>?</p>
39,482,142
10
1
null
2015-08-25 15:51:20.257 UTC
11
2022-08-06 13:53:45.39 UTC
null
null
null
null
978,690
null
1
55
laravel|laravel-5|phpunit
63,463
<p>Currently in 5.3 this is working...</p> <p><code>$content = $this-&gt;get('/v1/users/1')-&gt;response-&gt;getContent()</code>;</p> <p>It does break the chain, however since <code>response</code> returns the response and not the test runner. So, you should make your chainable assertions before fetching the response, like so...</p> <p><code>$content = $this-&gt;get('/v1/users/1')-&gt;seeStatusCode(200)-&gt;response-&gt;getContent()</code>;</p>
6,247,018
How do you test code written against AWS API
<p>I'm writing an application in Java that will upload a file up to AWS S3. The file will be given to the application in an argument, not hardcoded. I'd like to write tests to ensure that the file actually gets uploaded to S3. The test will be written before the code for TDD. (I have actually already written the code, but I'd like to ingrain TDD practices into all of my work as a habit)</p> <p>How exactly would I go about doing this? I will be using JUnit as that's what I'm most familiar with.</p> <p>Thanks in advance for any help.</p>
6,247,061
6
1
null
2011-06-06 01:11:36.857 UTC
10
2019-05-29 19:37:15.21 UTC
null
null
null
null
681,188
null
1
20
java|testing|junit|tdd|amazon-web-services
21,324
<p>The actual uploading and the tests that are doing it are part of your <em>integration testing</em>, not the <em>unit testing</em>. If you wrap the S3 API in a very thin class, you will mock that class for unit testing of your business classes, and you will use the real implementation for integration testing.<br> If you have decided, your <em>business</em> classes to take directly the <em>AmazonS3 interface</em>, then for unit testing you have to mock that one.</p> <p>The actual <em>exploratory testing</em> (learning and verifying) if and how amazon s3 works is what you actually do in separate experimental setup.</p> <p>P.S. I do not recommend using the AmazonS3 interface directly in your business classes, rather, wrap it in a thin interface of yours, so that if you decide to change the 'back-end storage' you can easily change it.</p>
38,983,666
Validation failed Class must exist
<p>I have been (hours) trouble with associations in Rails. I found a lot of similar problems, but I couldn't apply for my case:</p> <p>City's class:</p> <pre><code>class City &lt; ApplicationRecord has_many :users end </code></pre> <p>User's class:</p> <pre><code>class User &lt; ApplicationRecord belongs_to :city validates :name, presence: true, length: { maximum: 80 } validates :city_id, presence: true end </code></pre> <p>Users Controller:</p> <pre><code>def create Rails.logger.debug user_params.inspect @user = User.new(user_params) if @user.save! flash[:success] = "Works!" redirect_to '/index' else render 'new' end end def user_params params.require(:user).permit(:name, :citys_id) end </code></pre> <p>Users View:</p> <pre><code>&lt;%= form_for(:user, url: '/user/new') do |f| %&gt; &lt;%= render 'shared/error_messages' %&gt; &lt;%= f.label :name %&gt; &lt;%= f.text_field :name %&gt; &lt;%= f.label :citys_id, "City" %&gt; &lt;select name="city"&gt; &lt;% @city.all.each do |t| %&gt; &lt;option value="&lt;%= t.id %&gt;"&gt;&lt;%= t.city %&gt;&lt;/option&gt; &lt;% end %&gt; &lt;/select&gt; end </code></pre> <p>Migrate:</p> <pre><code>class CreateUser &lt; ActiveRecord::Migration[5.0] def change create_table :user do |t| t.string :name, limit: 80, null: false t.belongs_to :citys, null: false t.timestamps end end </code></pre> <p>Message from console and browser:</p> <pre><code>ActiveRecord::RecordInvalid (Validation failed: City must exist): </code></pre> <p>Well, the problem is, the attributes from User's model that aren't FK they are accept by User.save method, and the FK attributes like citys_id are not. Then it gives me error message in browser saying that "Validation failed City must exist".</p> <p>Thanks</p>
38,986,580
8
1
null
2016-08-16 20:13:23.903 UTC
10
2021-01-07 06:11:29.663 UTC
2016-08-16 23:57:30.927 UTC
null
5,666,052
null
5,666,052
null
1
57
ruby-on-rails|validation|associations|model-associations|belongs-to
41,466
<p>Try the following:</p> <pre><code>belongs_to :city, optional: true </code></pre> <p>According to the <a href="https://edgeguides.rubyonrails.org/association_basics.html#optional" rel="noreferrer">new docs</a>:</p> <blockquote> <p>4.1.2.11 :optional</p> <p>If you set the :optional option to true, then the presence of the associated object won't be validated. <strong>By default, this option is set to false.</strong></p> </blockquote>
44,087,310
Google Cloud SDK install on OS X: (gcloud.components.list) Failed to fetch component listing from server
<p>I'm trying to install the Google Cloud SDK (<a href="https://cloud.google.com/sdk/docs/quickstart-mac-os-x" rel="noreferrer">https://cloud.google.com/sdk/docs/quickstart-mac-os-x</a>) and get this error:<br> <code>ERROR: (gcloud.components.list) Failed to fetch component listing from server. Check your network settings and try again.</code> </p> <p>Already tried updating OpenSSL and corresponding Python (also tried Python 2.7.8): </p> <pre><code>openssl version OpenSSL 1.0.2k 26 Jan 2017 python -V Python 2.7.13 </code></pre> <p>Python is also using this OpenSSL version:</p> <pre><code>&gt;&gt;&gt; import ssl &gt;&gt;&gt; ssl.OPENSSL_VERSION 'OpenSSL 1.0.2k 26 Jan 2017' </code></pre> <p>I'm running <code>mac OS 10.12.4</code></p> <p>I've also tried <code>brew cask install google-cloud-sdk</code> which effectively just downloads the normal version und executes the install.sh script. Same result.</p> <p>Further debugging showed, it's unable to load <code>https://dl.google.com/dl/cloudsdk/channels/rapid/components-2.json</code> and throws this error: <code>URLError: &lt;urlopen error timed out&gt;</code>. Loading this file via Python directly works:</p> <p><code>urllib2.urlopen('https://dl.google.com/dl/cloudsdk/channels/rapid/components-2.json')</code></p> <p>Any ideas? Also any hints how to further debug this, would be appreciated :)</p>
44,091,682
3
0
null
2017-05-20 14:52:59.193 UTC
11
2020-04-30 17:07:32.777 UTC
2017-05-20 23:01:52.533 UTC
null
375,047
null
375,047
null
1
16
python|macos|google-cloud-sdk
12,520
<p>After turning off ipv6 support, the tool works like a charm. Looks like gcloud can not work gracefully with ipv6...</p> <p>Disable ipv6:</p> <pre><code>networksetup -setv6off Wi-Fi </code></pre> <p>Enable ipv6:</p> <pre><code>networksetup -setv6automatic Wi-Fi </code></pre> <hr> <p>Note: While investigating this, I was also able to make it work by using a very long timeout — 120 seconds. This wouldn't be practical, though, for most use cases due to the long delays it would introduce for each command.</p> <p>The timeout is located in <code>google-cloud-sdk/lib/googlecloudsdk/core/updater/installers.py</code> at line 36 called <code>TIMEOUT_IN_SEC</code></p>
27,832,630
Merge changes using vimdiff
<p>In my case, I have two files file1 and file2. Using vimdiff, I want to merge the changes as follows:</p> <ol> <li>In first difference, place line from file1 above line from file2. It means difference such as <code>Listing 2</code> in file2 and <code>List 2</code> should be <code>List 2</code> followed by <code>Listing 2</code> in the merged file.</li> <li>Reverse case in another change.</li> </ol> <p>Snapshot is shown below.</p> <p><img src="https://i.stack.imgur.com/tAppj.png" alt="enter image description here"></p> <p>How can we achieve this using vimdiff?</p>
27,832,686
4
1
null
2015-01-08 03:53:09.42 UTC
34
2021-04-15 12:37:56.907 UTC
null
null
null
null
1,629,262
null
1
72
vim|diff
71,255
<p>You can switch back and forth between the two windows with <kbd>Ctrl</kbd><kbd>w</kbd><kbd>w</kbd>. You can copy from one window do a <kbd>Ctrl</kbd><kbd>w</kbd><kbd>w</kbd>, and then paste into the other. As you resolve differences, the highlights will change, and disappear.</p> <p>Take a look at this <a href="http://vimcasts.org/episodes/fugitive-vim-resolving-merge-conflicts-with-vimdiff/" rel="noreferrer">video</a>.</p>
21,638,563
Angularjs pubsub vs $broadcast
<p>I've been reading up on event passing in Angularjs and I'm not convinced that using $broadcast is a good idea.</p> <p>Blogs like this <a href="http://www.objectpartners.com/2013/08/09/i-wish-i-knew-then-what-i-know-now-life-with-angularjs/">one</a> advocate getting used to $on even though it "felt like overkill."</p> <p>My confusion is that the implementation uses a depth-first traversal of the scopes and looks for subscribers, which makes the speed of your events dependent on your tree structure. Here is some code from that in angular:</p> <pre><code>// Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $digest if (!(next = (current.$$childHead || (current !== target &amp;&amp; current.$$nextSibling)))) { while(current !== target &amp;&amp; !(next = current.$$nextSibling)) { current = current.$parent; } } </code></pre> <p>Additionally, it seems like you would be able to hack dependency injection using these methods.</p> <p>The alternative is simply a service that caches event types and callbacks, and calls them directly. This requires that you clean up the subscriptions to avoid leaks.</p> <p>My question is, is there anything I'm missing about the motivation for the $broadcast/$on paradigm? Or is there any benefit to use it over a more traditional pubsub?</p> <p>Let me know if I'm not being clear enough with my question, and thanks for your time.</p>
21,639,013
2
1
null
2014-02-07 21:59:26.447 UTC
6
2015-03-05 20:11:43.253 UTC
null
null
null
null
2,728,255
null
1
32
javascript|angularjs|publish-subscribe
9,142
<p>I don't think you are missing anything. You've successfully outlined the pros/cons of each approach.</p> <p>The <code>$broadcast</code>/<code>$on</code> approach doesn't require you to unsubscribe, but it is not terribly efficient as it broadcasts to all the scopes. It also has a very low barrier to entry. You don't need to inject any services, you don't need to create them. They broadcast to everyone, so it is a more simple approach.</p> <p>The pub/sub approach is much more direct. Only subscribers get the events, so it isn't going to every scope in the system to make it work. It is more complex, however, because you need to write your service with callback handlers, and you have to remember to unsubscribe. The remembering to unsubscribe is pretty huge in my opinion. If you don't get this right, you get memory leaks. And you won't know it until it is a problem in 3 months.</p> <p>I can see why the built-in approach is <code>$broadcast</code>.</p>
33,033,747
Remove all previous versions of python
<p>I have some experience with <code>C++</code> and <code>Fortran</code>, and I want to start using <code>python</code> for my post-processing as I am starting to realise how inefficient <code>MATLAB</code> is for what I need to do (mostly involves plots with millions of points). </p> <p>I already had a few versions of <code>python</code> installed, from every time I wanted to start using. It has now become a mess. In <code>/usr/local/bin/</code>, here is what the command <code>ls python*</code> returns:</p> <pre><code>python python2.7 python3 python3.5 python3.5m pythonw-32 python-32 python2.7-32 python3-32 python3.5-32 python3.5m-config pythonw2.7 python-config python2.7-config python3-config python3.5-config pythonw pythonw2.7-32 </code></pre> <p>I now want a clean slate. I want a safe way to remove all the previous versions of <code>python</code>, including all of their packages, so I can just install the latest version and import all the libraries I want like <code>numpy</code> and <code>matplotlib</code> smoothly (I had some issues with that). </p> <p><strong>EDIT:</strong></p> <p>I am running on OSX Yosemite 10.10.</p>
33,034,184
1
1
null
2015-10-09 08:43:33.617 UTC
4
2015-10-09 09:05:07.19 UTC
2015-10-09 08:50:01.503 UTC
null
1,236,187
null
1,236,187
null
1
9
python|uninstallation
45,164
<p>Do not uninstall your system's Python interpreter (Python 2.7 most probably). You might consider uninstalling the other version (Python 3.5 most probably), but I do not think you really need to do that (it may not be a bad idea to keep a system-wide Python 3 interpreter... who knows!).</p> <p>If you want a clean state I would recommend you to use virtual environments for now on. You have two options:</p> <ul> <li>Use <a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/" rel="noreferrer"><code>virtualenv</code></a> and <a href="https://pypi.python.org/pypi/pip" rel="noreferrer"><code>pip</code></a> to setup your virtual environments and packages. However, using <code>pip</code> means you will have to compile the packages that need compilation (<code>numpy</code>, <code>matplotlib</code> and many other scientific Python packages that you may use for your "post-processing").</li> <li>Use Conda (or <a href="http://conda.pydata.org/miniconda.html" rel="noreferrer">Miniconda</a>). This way you will be able to handle virtual environments but without having to compile Python packages yourself. Conda also allows you to handle different Python interpreters without the need of having them installed in your system (it will download them for you).</li> </ul> <p>Also, you say you are feeling MATLAB is inefficient for plotting millions of points. I do not know your actual needs/constraints, but I find Matplotlib to be very inefficient for plotting large data and/or real-time data.</p> <p>Just as a suggestion, consider using <a href="http://www.pyqtgraph.org/" rel="noreferrer">PyQtGraph</a>. If you still feel that is not fast enough, consider using VisPy (probably less functional/convenient at the moment, but more <a href="http://vispy.org/" rel="noreferrer">efficient</a>).</p>
9,590,034
getting bash variable into filename for zip command
<p>In a bash script, how do I use a variable to create a specifically named zipped file? For example, I would like to do something like:</p> <pre><code>VERSION_STRING='1.7.3' zip -r foo.$VERSION_STRING foo </code></pre> <p>Where I ideally end up with a file called <code>foo.1.7.3.zip</code></p> <p>It seems like I'm having 2 problems:</p> <ol> <li>the zip command is treating <code>$VERSION_STRING</code> like it's null or empty</li> <li>the <code>.</code> after <code>foo</code> also seems to be mucking it up</li> </ol>
9,590,065
3
0
null
2012-03-06 18:54:33.227 UTC
5
2012-03-06 19:02:22.973 UTC
null
null
null
null
208,770
null
1
28
bash|zip
51,625
<p>The following works fine here using bash 4.1.5:</p> <pre><code>#!/bin/bash VERSION_STRING='1.7.3' echo zip -r foo foo.$VERSION_STRING.zip </code></pre> <p>I've added the <code>echo</code> to see the actual command rather than run it. The script prints out</p> <pre><code>zip -r foo foo.1.7.3.zip </code></pre>
9,325,569
Variable scoping in PowerShell
<p>A sad thing about PowerShell is that function and scriptblocks are dynamically scoped.</p> <p>But there is another thing that surprised me is that variables behave as a copy-on-write within an inner scope.</p> <pre><code>$array=@("g") function foo() { $array += "h" Write-Host $array } &amp; { $array +="s" Write-Host $array } foo Write-Host $array </code></pre> <p>The output is:</p> <pre><code>g s g h g </code></pre> <p>Which makes dynamic scoping a little bit less painful. But how do I avoid the copy-on-write?</p>
9,325,746
4
0
null
2012-02-17 09:14:01.993 UTC
11
2019-08-30 12:34:44.213 UTC
2015-01-10 00:32:19.613 UTC
null
63,550
null
343,957
null
1
69
powershell|scope
126,189
<p>You can use <em>scope modifiers</em> or the <code>*-Variable</code> cmdlets.</p> <p>The scope modifiers are:</p> <ul> <li><code>global</code> used to access/modify at the outermost scope (eg. the interactive shell)</li> <li><code>script</code> used on access/modify at the scope of the running script (<code>.ps1</code> file). If not running a script then operates as <code>global</code>.</li> </ul> <p>(For the <code>-Scope</code> parameter of the <code>*-Variable</code> cmdlets see the help.)</p> <p>Eg. in your second example, to directly modify the global <code>$array</code>:</p> <pre><code>&amp; { $global:array +="s" Write-Host $array } </code></pre> <p>For more details see the help topic <i><a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes?view=powershell-5.1" rel="noreferrer">about_scopes</a></i>.</p>
9,016,650
What is routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
<p>What is <code>routes.IgnoreRoute("{resource}.axd/{*pathInfo}")</code></p> <p>I cannot find any .axd file in my project, can I remove this route rule?</p>
9,016,704
5
0
null
2012-01-26 10:20:34.34 UTC
18
2020-02-01 15:09:21.103 UTC
2012-07-30 16:07:18.14 UTC
null
727,208
null
939,713
null
1
99
asp.net-mvc|asp.net-mvc-3|asp.net-mvc-routing
67,816
<p>.axd files don't exist physically. ASP.NET uses URLs with .axd extensions (ScriptResource.axd and WebResource.axd) internally, and they are handled by an HttpHandler.</p> <p>Therefore, you should keep this rule, to prevent ASP.NET MVC from trying to handle the request instead of letting the dedicated HttpHandler do it.</p>
22,924,300
Removing Data From ElasticSearch
<p>I'm new to <a href="http://www.elasticsearch.org/">ElasticSearch</a>. I'm trying to figure out how to remove data from ElasticSearch. I have deleted my indexes. However, that doesn't seem to actually remove the data itself. The other stuff I've seen points to the <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-delete-by-query.html">Delete by Query</a> feature. However, I'm not even sure what to query on. I know my indexes. Essentially, I'd like to figure out how to do a </p> <pre><code>DELETE FROM [Index] </code></pre> <p>From PostMan in Chrome. However, I'm not having any luck. It seems like no matter what I do, the data hangs around. Thus far, I've successfully deleted the indexes by using the DELETE HTTP Verb in PostMan and using a url like:</p> <pre><code> http://localhost:9200/[indexName] </code></pre> <p>However, that doesn't seem to actually remove the data (aka docs) themselves.</p>
22,932,471
24
1
null
2014-04-07 22:31:42.42 UTC
129
2022-06-14 08:20:16.94 UTC
2016-04-27 23:13:59.35 UTC
null
503,969
null
687,554
null
1
470
elasticsearch
807,246
<p>You can delete using <code>cURL</code> or visually using one of the many tools that open source enthusiasts have created for Elasticsearch. </p> <p><strong>Using cURL</strong></p> <pre><code>curl -XDELETE localhost:9200/index/type/documentID </code></pre> <p>e.g.</p> <pre><code>curl -XDELETE localhost:9200/shop/product/1 </code></pre> <p>You will then receive a reply as to whether this was successful or not. You can delete an entire index or types with an index also, you can delete a type by leaving out the document ID like so - </p> <pre><code>curl -XDELETE localhost:9200/shop/product </code></pre> <p>If you wish to delete an index -</p> <pre><code>curl -XDELETE localhost:9200/shop </code></pre> <p>If you wish to delete more than one index that follows a certain naming convention (note the <code>*</code>, a wildcard), -</p> <pre><code>curl -XDELETE localhost:9200/.mar* </code></pre> <p><strong>Visually</strong></p> <p>There are various tools as mentioned above, I wont list them here but I will link you to one which enables you to get started straight away, located <a href="http://lmenezes.com/elasticsearch-kopf/" rel="noreferrer">here</a>. This tool is called KOPF, to connect to your host please click on the logo on top left hand corner and enter the URL of your cluster.</p> <p>Once connected you will be able to administer your entire cluster, delete, optimise and tune your cluster.</p>
7,142,091
In PHP what does |= mean, That is pipe equals (not exclamation)
<p>I just found this in some code and I can't find anything on the web or php manual. Most likely since its an irregular character.</p> <p>Here is one of the lines that uses it.</p> <pre><code>$showPlayer |= isset($params['node']) &amp;&amp; $params['node']; </code></pre>
7,142,105
2
1
null
2011-08-22 00:23:33.53 UTC
4
2011-08-22 00:26:17.223 UTC
2011-08-22 00:25:51.967 UTC
null
218,196
null
465,199
null
1
29
php
9,077
<p><code>|=</code> is to <code>|</code> as <code>+=</code> is to <code>+</code>; that is, <code>$a |= $b;</code> is the same as <code>$a = $a | $b;</code>. The <code>|</code> operator is <a href="http://www.php.net/manual/en/language.operators.bitwise.php" rel="noreferrer">the bitwise OR operator</a>.</p>
7,485,212
"Not equal" sign in Visual Prolog?
<p>I can't find any documentation on &quot;not equal&quot; sign in Visual Prolog. Please provide the right solution of this problem:</p> <pre><code>class predicates sister : (string Person, string Sister) nondeterm(o,o). clauses sister(Person, Sister) :- Person [not-equal-sign] Sister, parent(Person, Parent), parent(Sister, Parent), woman(Sister). </code></pre>
7,485,430
2
0
null
2011-09-20 12:32:37.203 UTC
3
2020-07-31 00:17:48.24 UTC
2020-07-31 00:17:48.24 UTC
null
3,773,011
null
543,539
null
1
32
prolog|equals|clause|visual-prolog
105,725
<p>I don't know what do you mean by "not equal" (does not unify?), but you could try these:</p> <pre><code>X \= Y not(X = Y) \+ (X = Y) </code></pre>
31,378,232
Xcode Simulator animations extremely slow when played in editor
<p>Recently I have experienced, that Xcode's simulator has become extremely slow. Also if I create a new app and run it i, the transition between the launch screen and the first view controller takes about 3 seconds. Luckily it is only the iOS 9 simulator and not iOS 8 or lower. I have upgraded to Xcode 6.4 and I also have Xcode 7.0 beta 3 installed. Has anyone experienced the same? I have tried to uninstall both Xcode versions, but it didn't help.</p>
33,669,398
9
3
null
2015-07-13 08:04:50.317 UTC
28
2020-01-07 09:43:42.59 UTC
2018-04-10 19:14:45.167 UTC
null
3,641,812
null
1,011,150
null
1
114
ios|xcode|ios-simulator|simulator
48,852
<p>If you press command+T it triggers the 'Slow animations' feature. I didn't noticed this setting until now. Doh!</p>
31,285,911
Why let and var bindings behave differently using setTimeout function?
<p>This code logs <code>6</code>, 6 times:</p> <pre><code>(function timer() { for (var i=0; i&lt;=5; i++) { setTimeout(function clog() {console.log(i)}, i*1000); } })(); </code></pre> <p>But this code...</p> <pre><code>(function timer() { for (let i=0; i&lt;=5; i++) { setTimeout(function clog() {console.log(i)}, i*1000); } })(); </code></pre> <p>... logs the following result:</p> <pre><code>0 1 2 3 4 5 </code></pre> <p>Why?</p> <p>Is it because <code>let</code> binds to the inner scope each item differently and <code>var</code> keeps the latest value of <code>i</code>?</p>
31,286,220
2
4
null
2015-07-08 07:17:20.713 UTC
32
2019-03-13 15:17:34.77 UTC
2017-05-21 18:24:49.3 UTC
null
6,910,253
null
2,290,820
null
1
73
javascript|var|let
24,104
<p>With <strong><code>var</code></strong> you have a function scope, and only one shared binding for all of your loop iterations - i.e. the <code>i</code> in every setTimeout callback means <strong>the same</strong> variable that <strong>finally</strong> is equal to 6 after the loop iteration ends.</p> <p>With <strong><code>let</code></strong> you have a block scope and when used in the <code>for</code> loop you get a new binding for each iteration - i.e. the <code>i</code> in every setTimeout callback means <strong>a different</strong> variable, each of which has a different value: the first one is 0, the next one is 1 etc.</p> <p>So this:</p> <pre><code>(function timer() { for (let i = 0; i &lt;= 5; i++) { setTimeout(function clog() { console.log(i); }, i * 1000); } })(); </code></pre> <p>is equivalent to this using only var:</p> <pre><code>(function timer() { for (var j = 0; j &lt;= 5; j++) { (function () { var i = j; setTimeout(function clog() { console.log(i); }, i * 1000); }()); } })(); </code></pre> <p>using immediately invoked function expression to use function scope in a similar way as the block scope works in the example with <code>let</code>.</p> <p>It could be written shorter without using the <code>j</code> name, but perhaps it would not be as clear:</p> <pre><code>(function timer() { for (var i = 0; i &lt;= 5; i++) { (function (i) { setTimeout(function clog() { console.log(i); }, i * 1000); }(i)); } })(); </code></pre> <p>And even shorter with arrow functions:</p> <pre><code>(() =&gt; { for (var i = 0; i &lt;= 5; i++) { (i =&gt; setTimeout(() =&gt; console.log(i), i * 1000))(i); } })(); </code></pre> <p>(But if you can use arrow functions, there's no reason to use <code>var</code>.)</p> <p>This is how Babel.js translates your example with <code>let</code> to run in environments where <code>let</code> is not available:</p> <pre><code>"use strict"; (function timer() { var _loop = function (i) { setTimeout(function clog() { console.log(i); }, i * 1000); }; for (var i = 0; i &lt;= 5; i++) { _loop(i); } })(); </code></pre> <p>Thanks to <a href="https://stackoverflow.com/users/1202830/michael-geary">Michael Geary</a> for posting the link to Babel.js in the comments. See the link in the comment for a live demo where you can change anything in the code and watch the translation taking place immediately. It's interesting to see how other ES6 features get translated as well.</p>
11,963,599
SELECT with UNION AND LEFT JOIN
<p>Hi guys i've been trying this sql search query to my website search facility it supposed to search and order by relevance. It is working without the left join and I can't get it to work with left join. Here is the SQL query.</p> <pre><code>SELECT bl_albums.*, bl_bands.name as bandname, bl_bands.id as bandid, bl_bands.bandpage as bandpage, sum(relevance) FROM bl_albums LEFT JOIN( SELECT bl_albums.*, bl_bands.name as bandname, bl_bands.id as bandid, bl_bands.bandpage as bandpage,10 AS relevance FROM bl_albums WHERE bl_albums.name like 'Camera' UNION SELECT bl_albums.*, bl_bands.name as bandname, bl_bands.id as bandid, bl_bands.bandpage as bandpage, 7 AS relevance FROM bl_albums WHERE bl_albums.name like 'Camera%' UNION SELECT bl_albums.*, bl_bands.name as bandname, bl_bands.id as bandid, bl_bands.bandpage as bandpage, 5 AS relevance FROM bl_albums WHERE bl_albums.name like '%Camera' UNION SELECT bl_albums.*, bl_bands.name as bandname, bl_bands.id as bandid, bl_bands.bandpage as bandpage, 2 AS relevance FROM bl_albums WHERE bl_albums.name like '%Camera%' ) bl_bands on bl_albums.bandid = bl_bands.id GROUP BY bl_albums.name ORDER BY relevance desc </code></pre> <p>all table names are correct and all column names are correct. </p>
11,964,784
2
1
null
2012-08-15 03:03:42.183 UTC
1
2012-08-15 06:07:22.68 UTC
2012-08-15 03:06:23.4 UTC
null
625,440
null
1,376,251
null
1
1
sql
38,544
<p>Your subquery that you've named 'bl_bands' doesn't have bl_bands.id because all the union joins don't include the bl_bands table. Try adding joins to each union, if my assumption on all your data is correct:</p> <pre><code>SELECT bl_albums.*, bl_bands.name as bandname, bl_bands.id as bandid, bl_bands.bandpage as bandpage, sum(relevance) FROM bl_albums LEFT JOIN( SELECT bl_albums.*, bl_bands.name as bandname, bl_bands.id as bandid, bl_bands.bandpage as bandpage,10 AS relevance FROM bl_albums JOIN bl_bands ON bl_bands.id = bl_albums.bandid WHERE bl_albums.name like 'Camera' UNION SELECT bl_albums.*, bl_bands.name as bandname, bl_bands.id as bandid, bl_bands.bandpage as bandpage, 7 AS relevance FROM bl_albums JOIN bl_bands ON bl_bands.id = bl_albums.bandid WHERE bl_albums.name like 'Camera%' UNION SELECT bl_albums.*, bl_bands.name as bandname, bl_bands.id as bandid, bl_bands.bandpage as bandpage, 5 AS relevance FROM bl_albums JOIN bl_bands ON bl_bands.id = bl_albums.bandid WHERE bl_albums.name like '%Camera' UNION SELECT bl_albums.*, bl_bands.name as bandname, bl_bands.id as bandid, bl_bands.bandpage as bandpage, 2 AS relevance FROM bl_albums JOIN bl_bands ON bl_bands.id = bl_albums.bandid WHERE bl_albums.name like '%Camera%' ) bl_bands ON bl_albums.bandid = bl_bands.id GROUP BY bl_albums.name ORDER BY relevance desc </code></pre> <p>It looks like you might have copied/pasted some SELECT statements/column names but didn't add the joining in that you needed to get the results.</p>
58,473,656
malformed module path "xxxx/xxxx/uuid" missing dot in first path element when migrating from GOPATH based dep to go mod
<pre> $ go version 1.13.3 </pre> <p>I have a folder structure as follows:</p> <pre><code>GOPATH +---src +--- my-api-server +--- my-auth-server +--- main.go +--- my-utils +--- uuid +--- uuid.go </code></pre> <p><code>my-auth-server</code> uses <code>my-api-server/my-utils/uuid</code> as a depenency</p> <p>Now, when I used the GOPATH based module system, this worked fine. But when using go modules, when I run <code>go run main.go</code> in <code>my-auth-server</code> it returned error:</p> <pre><code>build command-line-arguments: cannot load my-api-server/my-utils/uuid: malformed module path "my-api-server/my-utils/uuid": missing dot in first path element </code></pre> <p>Any idea how to solve this?</p>
58,563,894
6
1
null
2019-10-20 13:49:10.64 UTC
3
2022-06-13 17:03:15.867 UTC
null
null
null
null
6,021,597
null
1
27
go|go-modules
43,771
<p>The <code>go.mod</code> file should be at the root of your project (in this case, <code>my-api-server/go.mod</code>).</p> <p>The first part of the module path should be a domain/path. For example, the full path might be <code>github.com/your-github-username/my-api-server</code>. The error you're seeing is because the first part is not a domain (with a period). You don't have to publish the module to develop it, but you need to use a proper domain name.</p> <p>Once you have a module path, you can import packages contained in that module using the full module path + "/" + the relative path of the package. For example,</p> <pre><code>import "github.com/your-github-username/my-api-server/my-utils/uuid" </code></pre> <p>Since <code>main.go</code> and <code>uuid</code> are contained in the same module, you don't need a <code>require</code> statement in the <code>go.mod</code> file to use the <code>uuid</code> package. You can import it like any other package and it will work.</p> <p>I recommend using <code>go build</code> and running the resulting executable rather than using <code>go run</code> to make sure you include all of the files you need in the build process.</p> <p>See <a href="https://blog.golang.org/using-go-modules" rel="noreferrer">https://blog.golang.org/using-go-modules</a> for a walkthrough of how to use Go modules, including the <a href="https://blog.golang.org/migrating-to-go-modules" rel="noreferrer">second post</a> in that series about how to convert a project to use modules.</p>
35,786,072
NullPointerException - Attempt to invoke virtual method RecyclerView$ViewHolder.shouldIgnore()' on a null object reference
<p>Several developers have reported seeing the following stack trace since upgrading to Android Support 23.2.0:</p> <pre><code>java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.support.v7.widget.RecyclerView$ViewHolder.shouldIgnore()' on a null object reference at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2913) at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1445) at android.support.v7.widget.RecyclerView.access$400(RecyclerView.java:144) at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:282) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:821) at android.view.Choreographer.doCallbacks(Choreographer.java:606) at android.view.Choreographer.doFrame(Choreographer.java:575) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:807) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:6895) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) </code></pre> <p>This occurs when RecyclerView's change animation is enabled and corresponding RecyclerView.Adapter methods notifyItemInserted(), notifyItemRemoved(), etc., are called to indicate that an isolated change was made to the list managed by the adapter (as opposed to a wholesale change, as indicated by notifyDataSetChanged()).</p> <p>Is this due to a bug in RecyclerView, or are we developers doing something wrong?</p>
35,786,073
9
2
null
2016-03-04 00:54:56.447 UTC
7
2022-02-21 23:16:49.117 UTC
null
null
null
null
315,702
null
1
34
android|android-support-library|android-recyclerview
22,157
<p>This appears to be due to a bug in RecyclerView, which was introduced in 23.2.0. The bug was reported <a href="https://code.google.com/p/android/issues/detail?id=199176" rel="noreferrer">here</a>, and I explained what I think is causing the error in <a href="https://code.google.com/p/android/issues/detail?id=199176#c5" rel="noreferrer">comment #5</a> on that bug.</p> <p>Here's my explanation, copied here for historical purposes and ease of reference:</p> <blockquote> <p>I found the source of this problem. Within RecyclerView.dispatchLayoutStep3(), there's a for loop, "for (int i = 0; i &lt; count; ++i)", where count is based on mChildHelper.getChildCount(). While this iteration is occurring, the collection managed by ChildHelper is modified by ChildHelper.hideViewInternal(), which results in null being returned from the call to mChildHelper.getChildAt() on line 3050 of RecyclerView, which in turn results in null being returned from getChildViewHolderInt() on the same line of code (RecyclerView:3050).</p> <p>Here's the chain of method calls that results in the modification that breaks the integrity of the for loop:</p> <p>dispatchLayoutStep3() -> animateChange() -> addAnimatingView() -> hide() -> hideViewInternal()</p> <p>When ChildHelper adds the child param to its mHiddenViews collection, it violates the integrity of the for loop way up in dispatchLayoutStep3().</p> <p>I see two workarounds for this: </p> <p>1) Disable change animation in your RecyclerView</p> <p>2) Downgrade to 23.1.1, where this wasn't a problem</p> </blockquote>
21,225,361
Is there anything like asynchronous BlockingCollection<T>?
<p>I would like to <code>await</code> on the result of <code>BlockingCollection&lt;T&gt;.Take()</code> asynchronously, so I do not block the thread. Looking for anything like this:</p> <pre><code>var item = await blockingCollection.TakeAsync(); </code></pre> <p>I know I could do this:</p> <pre><code>var item = await Task.Run(() =&gt; blockingCollection.Take()); </code></pre> <p>but that kinda kills the whole idea, because another thread (of <code>ThreadPool</code>) gets blocked instead.</p> <p>Is there any alternative?</p>
21,225,922
4
3
null
2014-01-20 02:30:49.99 UTC
27
2020-09-13 16:33:18.527 UTC
null
null
null
null
2,674,222
null
1
103
c#|.net|collections|task-parallel-library|async-await
26,551
<p>There are four alternatives that I know of.</p> <p>The first is <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.channels" rel="noreferrer">Channels</a>, which provides a threadsafe queue that supports asynchronous <code>Read</code> and <code>Write</code> operations. Channels are highly optimized and optionally support dropping some items if a threshold is reached.</p> <p>The next is <code>BufferBlock&lt;T&gt;</code> from <a href="http://msdn.microsoft.com/en-us/library/hh228603%28v=vs.110%29.aspx" rel="noreferrer">TPL Dataflow</a>. If you only have a single consumer, you can use <code>OutputAvailableAsync</code> or <code>ReceiveAsync</code>, or just link it to an <code>ActionBlock&lt;T&gt;</code>. For more information, <a href="https://blog.stephencleary.com/2012/11/async-producerconsumer-queue-using.html" rel="noreferrer">see my blog</a>.</p> <p>The last two are types that I created, available in my <a href="https://www.nuget.org/packages/Nito.AsyncEx/" rel="noreferrer">AsyncEx library</a>.</p> <p><a href="http://dotnetapis.com/pkg/Nito.AsyncEx/4.0.1/net45/doc/Nito.AsyncEx.AsyncCollection&#39;1" rel="noreferrer"><code>AsyncCollection&lt;T&gt;</code></a> is the <code>async</code> near-equivalent of <code>BlockingCollection&lt;T&gt;</code>, capable of wrapping a concurrent producer/consumer collection such as <code>ConcurrentQueue&lt;T&gt;</code> or <code>ConcurrentBag&lt;T&gt;</code>. You can use <code>TakeAsync</code> to asynchronously consume items from the collection. For more information, <a href="https://blog.stephencleary.com/2012/12/async-producer-consumer-queue-3-more.html" rel="noreferrer">see my blog</a>.</p> <p><a href="http://dotnetapis.com/pkg/Nito.AsyncEx/4.0.1/net45/doc/Nito.AsyncEx.AsyncProducerConsumerQueue&#39;1" rel="noreferrer"><code>AsyncProducerConsumerQueue&lt;T&gt;</code></a> is a more portable <code>async</code>-compatible producer/consumer queue. You can use <code>DequeueAsync</code> to asynchronously consume items from the queue. For more information, <a href="https://blog.stephencleary.com/2012/12/async-producer-consumer-queue-2-more.html" rel="noreferrer">see my blog</a>.</p> <p>The last three of these alternatives allow synchronous and asynchronous puts and takes.</p>
18,423,019
How to enable load time / runtime weaving with Hibernate JPA and Spring Framework
<p>I'm using Hibernate as a JPA provider (I'm using its <code>EntityManagerFactory</code> instead of its <code>SessionFactory</code>) in a Spring Framework application. I managed to get Spring Framework's load time weaving support working, so I'm past that hurdle.</p> <p>I need to enable lazy loading of <code>byte[]</code> and <code>@ManyToOne</code> properties on an entity. I understand how to instrument (weave) my entities at <em>build</em> time using Hibernate's ant task, but I'd like to instrument my entities at <em>runtime</em> instead (load time weaving). I've seen references to in on several Google search results, but no actual instructions for enabling it. What property do I need to set to instruct Hibernate that it can instrument my entities at runtime?</p>
18,423,704
2
0
null
2013-08-24 20:53:49.203 UTC
8
2017-01-20 11:39:10.023 UTC
null
null
null
null
1,653,225
null
1
8
spring|hibernate|jpa|hibernate-entitymanager|load-time-weaving
9,223
<p>After considerable reading of code and debugging, I figured this out. It's a shame the Hibernate ORM documentation doesn't include this information. (To be fair, the <a href="http://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/configuration.html#setup-configuration-bootstrapping">Hibernate EntityManager documentation</a> does, but it's not easily found. The <a href="http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch20.html#performance-fetching-lazyproperties">Hibernate instructions on "Using lazy property fetching"</a> only says, "Lazy property loading requires buildtime bytecode instrumentation." It does <em>not</em> mention that you can use <em>runtime</em> instrumentation with a Hibernate EntityManager property.)</p> <p>The first thing you must do is set the <code>"hibernate.ejb.use_class_enhancer"</code> JPA property to <code>"true"</code> (<code>String</code>). This tells Hibernate that it may use the "application server" class transformation by calling <code>addTransformer</code> on the <code>PersistenceUnitInfo</code> instance. The "application server" class transformation is really Spring's <code>LoadTimeWeaver</code>. If you are using Spring's Java configuration and <code>LocalContainerEntityManagerFactoryBean</code>, and Hibernate is a compile-time dependency, you could use the <code>AvailableSettings.USE_CLASS_ENHANCER</code> constant instead of the string-literal <code>"hibernate.ejb.use_class_enhancer"</code> (which would make it typo-resistant).</p> <p>If you are using Spring's Java configuration, there is an additional step you must take until <a href="https://jira.springsource.org/browse/SPR-10856">SPR-10856</a> is fixed. <code>LocalContainerEntityManagerFactoryBean</code>'s <code>setLoadTimeWeaver</code> method is not called automatically like it should be, so you must call it manually. In your <code>@Configuration</code> class, just <code>@Inject</code> or <code>@Autowire</code> a <code>LoadTimeWeaver</code> instance and call <code>setLoadTimeWeaver</code> manually when you are creating the <code>LocalContainerEntityManagerFactoryBean</code>.</p> <p>With these steps taken, I'm now using Hibernate's runtime entity bytecode instrumentation with Spring Framework in Tomcat.</p>
2,183,863
How to set height , width to image using jquery
<p>Is there any way to set height and width of an image using jquery? The following is my code </p> <pre><code>var img = new Image(); // Create image $(img).load(function(){ imgdiv.append(this); }).error(function () { $('#adsloder').remove(); }).attr({ id: val.ADV_ID, src: val.ADV_SRC, title: val.ADV_TITLE, alt: val.ADV_ALT }); </code></pre> <p>Thanks.</p>
2,183,876
3
0
null
2010-02-02 12:15:30.987 UTC
3
2018-05-21 07:00:43.12 UTC
2012-03-06 11:49:56.75 UTC
null
703,019
null
187,570
null
1
15
jquery
63,617
<p>You can call the <a href="http://api.jquery.com/height/" rel="noreferrer">.height()</a> and ,<a href="http://api.jquery.com/width/" rel="noreferrer">.width()</a> setters:</p> <pre><code>var img = new Image(); // Create image $(img).load(function(){ imgdiv.append(this); }).error(function () { $('#adsloder').remove(); }).attr({ id: val.ADV_ID, src: val.ADV_SRC, title: val.ADV_TITLE, alt: val.ADV_ALT }).height(100).width(100); </code></pre>
2,080,774
Generating interaction variables in R dataframes
<p>Is there a way - other than a for loop - to generate new variables in an R dataframe, which will be all the possible 2-way interactions between the existing ones? i.e. supposing a dataframe with three numeric variables V1, V2, V3, I would like to generate the following new variables:</p> <pre><code>Inter.V1V2 (= V1 * V2) Inter.V1V3 (= V1 * V3) Inter.V2V3 (= V2 * V3) </code></pre> <p>Example using for loop :</p> <pre><code>x &lt;- read.table(textConnection(' V1 V2 V3 V4 1 9 25 18 2 5 20 10 3 4 30 12 4 4 34 16' ), header=TRUE) dim.init &lt;- dim(x)[2] for (i in 1: (dim.init - 1) ) { for (j in (i + 1) : (dim.init) ) { x[dim(x)[2] + 1] &lt;- x[i] * x[j] names(x)[dim(x)[2]] &lt;- paste("Inter.V",i,"V",j,sep="") } } </code></pre>
2,082,278
3
0
null
2010-01-17 11:18:12.25 UTC
14
2016-11-18 15:42:58.66 UTC
2010-01-17 13:07:16.007 UTC
null
170,792
null
170,792
null
1
25
r|dataframe
26,797
<p>Here is a one liner for you that also works if you have factors:</p> <pre><code>&gt; model.matrix(~(V1+V2+V3+V4)^2,x) (Intercept) V1 V2 V3 V4 V1:V2 V1:V3 V1:V4 V2:V3 V2:V4 V3:V4 1 1 1 9 25 18 9 25 18 225 162 450 2 1 2 5 20 10 10 40 20 100 50 200 3 1 3 4 30 12 12 90 36 120 48 360 4 1 4 4 34 16 16 136 64 136 64 544 attr(,"assign") [1] 0 1 2 3 4 5 6 7 8 9 10 </code></pre>
1,382,634
how to set cronjob for 2 days?
<p>We would like to use a cronjob to create a database backup.</p> <p>The backup should occur ones every two days. Can the following cron-entry be used?</p> <pre><code>0 0 2 * * * backup-command </code></pre> <p>If this is wrong please tell me the correct command for setting the cron for 2 days.</p>
1,382,638
3
0
null
2009-09-05 06:33:25.773 UTC
6
2018-11-02 11:26:53.72 UTC
2018-01-31 16:18:53.113 UTC
null
8,344,060
someone
null
null
1
42
cron
61,784
<p>From <a href="http://www.unixgeeks.org/security/newbie/unix/cron-1.html" rel="noreferrer">here</a>:</p> <blockquote> <p>Cron also supports 'step' values.</p> <p>A value of <code>*/2</code> in the dom field would mean the command runs every two days and likewise, <code>*/5</code> in the hours field would mean the command runs every 5 hours. e.g.</p> <pre><code>* 12 10-16/2 * * root backup.sh </code></pre> <p>is the same as:</p> <pre><code>* 12 10,12,14,16 * * root backup.sh </code></pre> </blockquote> <p>So I think you want <code>0 0 */2 * *</code>.</p> <p>What you've got (<code>0 0 2 * *</code>) will run the command on the 2nd of the month at midnight, every month.</p> <p>p.s. You seem to have an extra asterisk in your answer. The format should be:</p> <pre><code>minute hour dom month dow user cmd </code></pre> <p>So your extra asterisk would be in the <code>user</code> field. Is that intended?</p>
8,503,663
Force https://www. for Codeigniter in htaccess with mod_rewrite
<p>I'm using Codeigniter and following <a href="https://stackoverflow.com/questions/4398951/force-ssl-https-using-htaccess-and-mod-rewrite">these instructions</a> to force ssl but all requests are being redirected to</p> <pre><code>http://staging.example.com/index.php/https:/staging.example.com </code></pre> <p>My <code>.htaccess</code> is:</p> <pre><code>### Canonicalize codeigniter URLs # Enforce SSL https://www. RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] ### # Removes access to the system folder by users. # Additionally this will allow you to create a System.php controller, # previously this would not have been possible. # 'system' can be replaced if you have renamed your system folder. RewriteCond %{REQUEST_URI} ^system.* RewriteRule ^(.*)$ /index.php/$1 [L] # Checks to see if the user is attempting to access a valid file, # such as an image or css document, if this isn't true it sends the # request to index.php RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] </code></pre>
8,503,731
5
1
null
2011-12-14 11:22:33.19 UTC
8
2016-08-18 22:34:55.007 UTC
2017-05-23 12:10:16.147 UTC
null
-1
null
247,474
null
1
15
php|.htaccess|codeigniter|mod-rewrite
46,915
<p>I think, instead of</p> <pre><code>RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </code></pre> <p>you should have something like</p> <pre><code>RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </code></pre> <p>do have the rewrite rule match. Your link is currently produced by the third rule.</p>
19,554,996
Can't access WEB API with ip:port but can with localhost:port during VS debug mode
<p>I am trying to write an WEB API from .net and trying for my Android Application to query some data from the sql server database.</p> <p>I have the web api written and it works well in debug mode.</p> <p>My question is I notice the url of that application is <code>localhost:port</code> and it runs fine. However, when I try to change it to <code>MYIP:port (eg. http:192.168.X.1234)</code> or <code>MYHOSTNAME:port (eg win7home:1234)</code> this gives me <code>Bad Request - Invalid Hostname</code>.</p> <p>I know I can deploy this to IIS and my IIS is setup but I was just wondering how come it doesn't work in debug mode??? </p> <p>Is there a way for me to run it in debug mode and test in on my Android at the same time instead of having to deploy it every time I want to make a change?</p>
19,573,269
6
0
null
2013-10-24 00:53:51.747 UTC
13
2021-01-16 06:27:40.753 UTC
2013-10-24 00:58:22.517 UTC
null
2,335,799
null
1,446,102
null
1
46
c#|android|asp.net|debugging|localhost
84,975
<p>Both Anton and Matthew's Answers pointed me to the right direction</p> <p>So this what I did</p> <ol> <li><p>Run Visual Studios in administrator mode</p></li> <li><p>Changed the binding protocols and allow for incoming directions as suggested <a href="http://johan.driessen.se/posts/Accessing-an-IIS-Express-site-from-a-remote-computer" rel="noreferrer">http://johan.driessen.se/posts/Accessing-an-IIS-Express-site-from-a-remote-computer</a></p> <p>But after that, I have a service unavailable (503) error</p></li> <li><p>So I followed this : <a href="https://stackoverflow.com/questions/17048252/iis-express-enable-external-request-503">IIS Express Enable External Request - 503</a> Added just the port protocol and port:ip protocol, </p> <p> </p></li> </ol> <p>Than it works both on my machine's browser and on my phone.</p> <p>Not too too sure why the 3rd step is needed -my hypothesis is (the localhost url is needed for VS to point to and the ip url is used for accessing from another machine)</p>
19,477,324
How do I calculate the temperature in celsius returned in openweathermap.org JSON?
<p>I'm getting the weather for a city using openweathermap.org.</p> <p>The jsonp call is working and everything is fine but the resulting object contains the temperature in an unknown unit:</p> <pre><code>{ //... "main": { "temp": 290.38, // What unit of measurement is this? "pressure": 1005, "humidity": 72, "temp_min": 289.25, "temp_max": 291.85 }, //... } </code></pre> <p>Here is a demo that <code>console.log</code>'s the full object.</p> <p>I don't think the resulting temperature is in fahrenheit because converting <code>290.38</code> fahrenheit to celsius is <code>143.544</code>.</p> <p>Does anyone know what temperature unit openweathermap is returning?</p>
19,477,362
6
1
null
2013-10-20 12:30:23.957 UTC
12
2022-03-25 20:11:59.34 UTC
2016-03-11 14:26:42.797 UTC
null
1,946,501
null
414,385
null
1
49
javascript|json|units-of-measurement|weather-api|openweathermap
56,912
<p>It looks like <a href="http://en.wikipedia.org/wiki/Kelvin" rel="noreferrer">kelvin</a>. Converting kelvin to celsius is easy: Just subtract 273.15.</p> <p>Looking at <a href="http://openweathermap.org/api" rel="noreferrer">the API documentation</a>, if you add <code>&amp;units=metric</code> to your request, you'll get back celsius.</p>
422,784
How to fix closure problem in ActionScript 3 (AS3)
<p>In the code below I'm trying to load some images and put them in the stage as soon as they get individually loaded. But it is bugged since only the last image is displayed. I suspect it's a closure problem. How can I fix it? Isn't the behaviour of closures in AS3 the same as in Java Script ?</p> <pre><code>var imageList:Array = new Array(); imageList.push({'src':'image1.jpg'}); imageList.push({'src':'image2.jpg'}); var imagePanel:MovieClip = new MovieClip(); this.addChildAt(imagePanel, 0); for (var i in imageList) { var imageData = imageList[i]; imageData.loader = new Loader(); imageData.loader.contentLoaderInfo.addEventListener( Event.COMPLETE, function() { imagePanel.addChild(imageData.loader.content as Bitmap); trace('Completed: ' + imageData.src); }); trace('Starting: ' + imageData.src); imageData.loader.load(new URLRequest(imageData.src)); } </code></pre>
423,073
4
1
null
2009-01-08 00:37:02.47 UTC
10
2013-06-11 17:27:45.06 UTC
2011-05-12 08:20:19.883 UTC
Salty
236,831
fromvega
47,883
null
1
25
flash|apache-flex|actionscript-3|closures
6,134
<blockquote> <p>Isn't the behaviour of closures in AS3 the same as in Java Script ?</p> </blockquote> <p>Yes, JavaScript does exactly the same thing. As does Python. And others.</p> <p>Although you define 'var imageData' inside the 'for', for loops do not introduce a new scope in these languages; in fact the variable imageData is bound in the containing scope (the outer function, or in this case it appears to be global scope). You can verify this by looking at imageData after the loop has completed executing, and finding the last element of imageList in it.</p> <p>So there is only one imageData variable, not one for each iteration of the loop. When COMPLETE fires, it enters the closure and reads whatever value imageData has <em>now</em>, not at the time the function was defined(*). Typically the for-loop will have finished by the point COMPLETE fires and imageData will be holding that last element from the final iteration.</p> <p>(* - there exist 'early-binding' languages that <em>will</em> evaluate the variable's value at the point you define a closure. But ActionScript is not one of them.)</p> <p>Possible solutions tend to involve using an outer function to introduce a new scope. For example:</p> <pre><code>function makeCallback(imageData) { return function() { imagePanel.addChild(imageData.loader.content as Bitmap); trace('Completed: ' + imageData.src); } } ... imageData.loader.contentLoaderInfo.addEventListener(Event.COMPLETE, makeCallback(imageData)); </code></pre> <p>You /can/ put this inline, but the doubly-nested function() starts to get harder to read.</p> <p>See also Function.bind() for a general-purpose partial function application feature you could use to achive this. It's likely to be part of future JavaScript/ActionScript versions, and can be added to the language through prototyping in the meantime.</p>
731,407
Proper way to use JQuery when using MasterPages in ASP.NET?
<p>I have no issues when doing using JQuery in a aspx page without a masterpage, but when I try to use it in pages that have a masterpage, it doesn't work, so I end up putting the jquery files and other script files in the page instead of the master. Now if I have 10 pages, I am doing this for all 10, which I know is incorrect. In the sample masterpage below, where would I put my script files.</p> <pre><code>&lt;html&gt; &lt;head runat="server"&gt; &lt;asp:ContentPlaceHolder ID="head" runat="server"&gt; &lt;/asp:ContentPlaceHolder&gt; &lt;/head&gt; &lt;body&gt; &lt;asp:ContentPlaceHolder ID="ContentPanel" runat="server"&gt; &lt;/asp:ContentPlaceHolder&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I recently used the fancybox plugin and what I did was instead of putting the jquery script and fancybox scripts in the masterpage because I got frustrated on getting it to work, I just put it in the page where I wanted the script to run, specifically at the bottom, right before the closing asp:Content. Of course, now I have the issue of, if I wanted to use the fancybox plugin in other pages, I would put the jquery script and fancybox script on all 5 pages instead of just the masterpage. When dealing with masterpages, where does everything go using my example above?</p>
731,521
4
0
null
2009-04-08 19:08:47.107 UTC
15
2018-02-26 20:57:58.247 UTC
2012-07-11 22:29:40.343 UTC
null
699,978
null
33,690
null
1
40
asp.net|jquery|master-pages|fancybox
73,833
<p>You would declare your main jQuery scripts within the master page, as you would normally:</p> <pre><code>&lt;head runat="server"&gt; &lt;link href="/Content/Interlude.css" rel="Stylesheet" type="text/css" /&gt; &lt;script type="text/javascript" src="/Scripts/jquery-1.3.2.min.js"&gt;&lt;/script&gt; &lt;asp:ContentPlaceHolder ID="head" runat="server"&gt; &lt;/asp:ContentPlaceHolder&gt; &lt;/head&gt; </code></pre> <p>And then any page specific JS files could be loaded within the Content controls that reference the Head ContentPlaceholder.</p> <p>However, a better option would be to look into the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.aspx" rel="noreferrer">ScriptManager</a> and <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.aspx" rel="noreferrer">ScriptManagerProxy</a> controls - these can provide you with a lot more control over the way your JS files are served to the client.</p> <p>So you would place a ScriptManager control in you master page, and add a reference to the jQuery core code in that:</p> <pre><code>&lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;asp:ScriptManager ID="ScriptManager1" runat="server"&gt; &lt;Scripts&gt; &lt;asp:ScriptReference Path="/Scripts/jquery-1.3.2.min.js" /&gt; &lt;/Scripts&gt; &lt;/asp:ScriptManager&gt; </code></pre> <p>Then, in your page that requires some custom JS files, or a jQuery plugin, you can have:</p> <pre><code>&lt;asp:Content ID="bodyContent" ContentPlaceholderID="body"&gt; &lt;asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server"&gt; &lt;Scripts&gt; &lt;asp:ScriptReference Path="/Scripts/jquery.fancybox-1.2.1.pack.js" /&gt; &lt;/Scripts&gt; &lt;/asp:ScriptManagerProxy&gt; </code></pre> <p>The ScriptManager allows you to do things like control where on the page scripts are rendered with <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.loadscriptsbeforeui.aspx" rel="noreferrer">LoadScriptsBeforeUI</a> (or better yet, after by setting it to False).</p>
1,141,388
Cocoa - Notification on NSUserDefaults value change?
<p>Let's say I have a key <code>@"MyPreference"</code>, with a corresponding value stored through <code>NSUserDefaults</code>.</p> <p>Is there a way to be notified when the value is modified?</p> <p>Or could it be done through bindings? (But this case, instead of binding the value to a UI element, I wish my object to be notified of the change, so that I can perform other tasks.)</p> <p>I am aware that <code>NSUserDefaultsDidChangeNotification</code> can be observed, but this appears to be a all-or-nothing approach, and there does not appear to be a mechanism there to get at the specific key-value-pair that was modified. (Feel free to correct.)</p>
1,141,404
4
0
null
2009-07-17 03:58:40.413 UTC
25
2020-05-02 08:59:49.363 UTC
2020-05-02 08:58:57.603 UTC
null
3,641,812
null
78,396
null
1
53
cocoa|notifications|preferences
22,573
<p>Spent all day looking for the answer, only to find it 10 minutes after asking the question...</p> <p>Came across a solution through Key-Value-Observing:</p> <pre><code>[[NSUserDefaultsController sharedUserDefaultsController] addObserver:self forKeyPath:@"values.MyPreference" options:NSKeyValueObservingOptionNew context:NULL]; </code></pre> <p>Or, more simply (per comment below):</p> <pre><code>[[NSUserDefaults standardUserDefaults] addObserver:self forKeyPath:@"MyPreference" options:NSKeyValueObservingOptionNew context:NULL]; </code></pre>
1,197,401
Get element node at caret position (in contentEditable)
<p>Let's say I have some HTML code like this:</p> <pre><code>&lt;body contentEditable="true"&gt; &lt;h1&gt;Some heading text here&lt;/h1&gt; &lt;p&gt;Some text here&lt;/p&gt; &lt;/body&gt; </code></pre> <p>Now the caret (the blinking cursor) is blinking inside the <code>&lt;h1&gt;</code> element, let's say in the word <code>"|heading"</code>. </p> <p>How can I get the element the caret is in with JavaScript? Here I would like to get node name: <code>"h1"</code>.</p> <p>This needs to work only in WebKit (it's embedded in an application). It should preferably also work for selections. </p>
1,211,981
1
0
null
2009-07-29 00:01:07.723 UTC
7
2019-12-06 16:09:03 UTC
2019-12-06 16:09:03 UTC
null
104,380
null
146,752
null
1
37
javascript|dom|webkit|contenteditable|caret
16,870
<p>Firstly, think about <em>why</em> you're doing this. If you're trying to stop users from editing certain elements, just set <code>contenteditable</code> to false on those elements.</p> <p>However, it is possible to do what you ask. The code below works in Safari 4 and will return the node the selection is anchored in (i.e. where the user <em>started to select</em>, selecting "backwards" will return the end instead of the start) – if you want the element type as a string, just get the <code>nodeName</code> property of the returned node. This works for zero-length selections as well (i.e. just a caret position).</p> <pre><code>function getSelectionStart() { var node = document.getSelection().anchorNode; return (node.nodeType == 3 ? node.parentNode : node); } </code></pre>
21,830
PostgreSQL: GIN or GiST indexes?
<p>From what information I could find, they both solve the same problems - more esoteric operations like array containment and intersection (&amp;&amp;, @>, &lt;@, etc). However I would be interested in advice about when to use one or the other (or neither possibly).<br> The <a href="http://www.postgresql.org/docs/current/static/textsearch-indexes.html" rel="noreferrer">PostgreSQL documentation</a> has some information about this:</p> <ul> <li>GIN index lookups are about three times faster than GiST</li> <li>GIN indexes take about three times longer to build than GiST</li> <li>GIN indexes are about ten times slower to update than GiST</li> <li>GIN indexes are two-to-three times larger than GiST</li> </ul> <p>However I would be particularly interested to know if there is a performance impact when the memory to index size ration starts getting small (ie. the index size becomes much bigger than the available memory)? I've been told on the #postgresql IRC channel that GIN needs to keep all the index in memory, otherwise it won't be effective, because, unlike B-Tree, it doesn't know which part to read in from disk for a particular query? The question would be: is this true (because I've also been told the opposite of this)? Does GiST have the same restrictions? Are there other restrictions I should be aware of while using one of these indexing algorithms?</p>
26,398
1
1
null
2008-08-22 05:22:39.61 UTC
10
2017-06-07 04:49:44.357 UTC
2014-03-29 03:31:52.273 UTC
jsight
168,868
Cd-MaN
1,265
null
1
38
postgresql|indexing|gwt-gin|gist-index
18,811
<p>First of all, do you need to use them for text search indexing? GIN and GiST are index specialized for some data types. If you need to index simple char or integer values then the normal B-Tree index is the best.<br> Anyway, PostgreSQL documentation has a chapter on <a href="http://www.postgresql.org/docs/8.3/static/gist.html" rel="noreferrer">GIST</a> and one on <a href="http://www.postgresql.org/docs/8.3/static/gin.html" rel="noreferrer">GIN</a>, where you can find more info.<br> And, last but not least, the best way to find which is best is to generate sample data (as much as you need to be a real scenario) and then create a GIST index, measuring how much time is needed to create the index, insert a new value, execute a sample query. Then drop the index and do the same with a GIN index. Compare the values and you will have the answer you need, based on your data.</p>
53,807,511
pip cannot uninstall <package>: "It is a distutils installed project"
<p>I tried to install the Twilio module:</p> <pre><code>sudo -H pip install twilio </code></pre> <p>And I got this error:</p> <pre><code>Installing collected packages: pyOpenSSL Found existing installation: pyOpenSSL 0.13.1 Cannot uninstall 'pyOpenSSL'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall. </code></pre> <p>Anyone know how to uninstall pyOpenSSL?</p>
53,807,588
6
1
null
2018-12-16 23:51:49.55 UTC
18
2022-01-20 19:33:26.663 UTC
2021-01-21 05:50:17.863 UTC
null
6,573,902
null
9,900,360
null
1
104
python|installation|pip|distutils
167,344
<p>This error means that this package's metadata doesn't include a list of files that belong to it. <strong>Most probably, you have installed this package via your OS' package manager, so you need to use that rather than <code>pip</code> to update or remove it, too.</strong></p> <p>See e.g. <a href="https://github.com/pypa/pip/issues/5247#issuecomment-443398741" rel="noreferrer">Upgrading to pip 10: It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall. · Issue #5247 · pypa/pip</a> for one such example where the package was installed with <code>apt</code>.</p> <hr> <p>Alternatively, depending on your needs, it may be more productive to not use your system Python and/or its global environment but create a private Python installation and/or environment. There are many options here including <code>virtualenv</code>, <code>venv</code>, <code>pyenv</code>, <code>pipenv</code> and installing Python from source into <code>/usr/local</code> or <code>$HOME</code>/<code>$HOME/.local</code> (or <code>/opt/&lt;whatever&gt;</code>).</p> <hr> <p>Finally, I must comment on the often-suggested (e.g. at <a href="https://stackoverflow.com/questions/49932759/pip-10-and-apt-how-to-avoid-cannot-uninstall-x-errors-for-distutils-packages">pip 10 and apt: how to avoid &quot;Cannot uninstall X&quot; errors for distutils packages</a>) <code>--ignore-installed</code> <code>pip</code> switch.</p> <p>It <em>may</em> work (potentially for a long enough time for your business needs), but may just as well break things on the system in unpredictable ways. One thing is sure: it makes the system's configuration unsupported and thus unmaintainable -- because you have essentially overwritten files from your distribution with some other arbitrary stuff. E.g.:</p> <ul> <li>If the new files are binary incompatible with the old ones, other software from the distribution built to link against the originals will segfault or otherwise malfunction.</li> <li>If the new version has a different set of files, you'll end up with a mix of old and new files which may break dependent software as well as the package itself.</li> <li>If you change the package with your OS' package manager later, it will overwrite <code>pip</code>-installed files, with similarly unpredictable results.</li> <li>If there are things like configuration files, differences in them between the versions can also lead to all sorts of breakage.</li> </ul>
19,307,341
Android Library Gradle release JAR
<p>How can I release Jar packaging of <code>android-library</code> project?<br> I've found, classes.jar is located under <code>build/bundles/release/classes.jar</code> and I suppose this is correct Jar package (contains <code>*.class</code> files).</p> <p>Is there some official way, to release library as JAR instead of AAR ?</p> <p><strong>Edit</strong><br> I use Gradle to release Maven artifacts, and I'd like to release JAR along with AAR package. So JAR with signature, md5, manifest, ...<br> based on <a href="https://chris.banes.me/2013/08/27/pushing-aars-to-maven-central/" rel="noreferrer">https://chris.banes.me/2013/08/27/pushing-aars-to-maven-central/</a></p> <pre><code>apply plugin: 'maven' apply plugin: 'signing' configurations { archives { extendsFrom configurations.default } } def sonatypeRepositoryUrl if (isReleaseBuild()) { println 'RELEASE BUILD' sonatypeRepositoryUrl = "https://oss.sonatype.org/service/local/staging/deploy/maven2/" } else { println 'DEBUG BUILD' sonatypeRepositoryUrl = "https://oss.sonatype.org/content/repositories/snapshots/" } if(!hasProperty('nexusPassword')) { ext.set('nexusPassword', System.console().readPassword("\n\$ Type in password for Sonatype nexus account " + nexusUsername + ": ")) } if(!signing.hasProperty('password')) { ext.set('signing.password', System.console().readPassword("\n\$ Type in GPG key password: ")) } afterEvaluate { project -&gt; uploadArchives { repositories { mavenDeployer { beforeDeployment { MavenDeployment deployment -&gt; signing.signPom(deployment) } pom.artifactId = POM_ARTIFACT_ID repository(url: sonatypeRepositoryUrl) { authentication(userName: nexusUsername, password: nexusPassword) } pom.project { name POM_NAME packaging POM_PACKAGING description POM_DESCRIPTION url POM_URL scm { url POM_SCM_URL connection POM_SCM_CONNECTION developerConnection POM_SCM_DEV_CONNECTION } licenses { license { name POM_LICENCE_NAME url POM_LICENCE_URL distribution POM_LICENCE_DIST } } developers { developer { id "loopj" name "James Smith" } developer { id "smarek" name "Marek Sebera" } } } } } } signing { required { isReleaseBuild() &amp;&amp; gradle.taskGraph.hasTask("uploadArchives") } sign configurations.archives } task androidJavadocs(type: Javadoc) { source = android.sourceSets.main.java.srcDirs } task androidJavadocsJar(type: Jar) { classifier = 'javadoc' from androidJavadocs.destinationDir } task androidSourcesJar(type: Jar) { classifier = 'sources' from android.sourceSets.main.java.srcDirs } artifacts { archives androidSourcesJar archives androidJavadocsJar } } </code></pre> <p>using </p> <pre><code>task androidJar(type: Jar) { from android.sourceSets.main.java.srcDirs } </code></pre> <p>will package only java files, not compiled and linked against android sdk</p>
19,484,146
3
0
null
2013-10-10 22:31:04.19 UTC
40
2017-12-27 13:27:33.333 UTC
2015-05-30 05:08:01.663 UTC
null
1,713,757
null
492,624
null
1
63
java|android|jar|gradle|aar
23,062
<p>While I haven't tried uploading the artifacts with a deployment to Sonatype (or even a local repo), here's what I managed to come up with <a href="https://github.com/square/fest-android/pull/80">a few weeks ago</a> when trying to tackle the same problem.</p> <pre><code>android.libraryVariants.all { variant -&gt; def name = variant.buildType.name if (name.equals(com.android.builder.core.BuilderConstants.DEBUG)) { return; // Skip debug builds. } def task = project.tasks.create "jar${name.capitalize()}", Jar task.dependsOn variant.javaCompile task.from variant.javaCompile.destinationDir artifacts.add('archives', task); } </code></pre> <p>Then run the following:</p> <pre><code>./gradlew jarRelease </code></pre>
19,565,268
Add data into table/query from text box and button [Access]
<p>I am looking for help on trying to add data into a table / query through text boxes and a button. Currently, there are two buttons that will be hooked up to the text boxes; Search &amp; Add.</p> <p>Search I have finished already, where it searches a query attached to a table for the input you entered into the text boxes. Simple.</p> <p>Though now I'd also like to make an add button, where once you put information into the text boxes and click add instead of search, it directly adds that information onto the table and saves it so you can view it at later points in time.</p> <p>This is code I found online somewhere, but I don't know how to make it pick up the data from the text boxes using it:</p> <pre><code>Private Sub Command344_Click() INSERT INTO OrderT (CustomerName,OrderName,OrderDesc,DateOfPurchase,ProjectDueDate,EngineerDueDate,ProjectComplete,CutplanDueDate,MaterialSpecs,CutplanCode,HardwareSpecs,HardwareDueDate,HardwareComplete,PurchaseOrder,PurchaseSupplier); VALUES (CustomerName,OrderName,OrderDesc,DateOfPurchase,ProjectDueDate,EngineerDueDate,ProjectComplete,CutplanDueDate,MaterialSpecs,CutplanCode,HardwareSpecs,HardwareDueDate,HardwareComplete,PurchaseOrder,PurchaseSupplier); End Sub </code></pre> <p>Button Name: Command344</p> <p>TextBox Names: CustomerName OrderName OrderDesc DateOfPurchase ProjectDueDate EngineerDueDate ProjectComplete CutplanDueDate MaterialSpecs CutplanCode HardwareSpecs HardwareDueDate HardwareComplete PurchaseOrder PurchaseSupplier</p> <p>The fields in the table have the same names in the exact same order from top -> bottom, left -> right.</p> <p>The table name is OrderT.</p> <p>Form name is SearchF</p>
19,566,747
1
0
null
2013-10-24 11:56:36.333 UTC
2
2017-10-11 12:07:23.947 UTC
2013-10-24 12:21:10.037 UTC
null
77,335
null
2,915,607
null
1
1
ms-access|vba
72,042
<p>You can do this either through a query or by picking up the data from your form directly.</p> <p>To do this in a query, you would put something like this (untested) code behind your button:</p> <pre><code> Dim sSQL as String Set sSQL = "INSERT INTO OrderT (CustomerName,OrderName,OrderDesc,DateOfPurchase,ProjectDueDate,EngineerDueDate,ProjectComplete,CutplanDueDate,MaterialSpecs,CutplanCode,HardwareSpecs,HardwareDueDate,HardwareComplete,PurchaseOrder,PurchaseSupplier) VALUES (" &amp; Me.CustomerName &amp; "," &amp; Me.OrderName &amp; "," &amp; Me.OrderDesc &amp; "," &amp; Me.DateOfPurchase &amp; "," &amp; Me.ProjectDueDate &amp; "," &amp; Me.EngineerDueDate &amp; "," &amp; Me.ProjectComplete &amp; "," &amp; Me.CutplanDueDate &amp; "," &amp; Me.MaterialSpecs &amp; "," &amp; Me.CutplanCode &amp; "," &amp; Me.HardwareSpecs &amp; "," &amp; Me.HardwareDueDate &amp; "," &amp; Me.HardwareComplete &amp; "," &amp; PurchaseOrder &amp; "," &amp; Me.PurchaseSupplier &amp; ");" DoCmd.RunSQL sSQL </code></pre> <p>Picking up the data from the data form (my preferred method) would look like this (untested) code:</p> <pre><code>Dim db as Database Dim rec as Recordset Set db = CurrentDB set rec = db.OpenRecordset ("Select * from OrderT") rec.AddNew rec("CustomerName") = Me.CustomerName rec("OrderName") = Me.OrderName etc... rec.Update Set rec = Nothing Set db = Nothing </code></pre>
38,157,335
What does {:?} mean in a Rust format string?
<p>I found out that <code>{:?}</code> prints an entire array in Rust. I want to know what is it called and how exactly it works. Is it only limited to printing arrays or could it also be used elsewhere for other purposes?</p>
38,157,410
2
0
null
2016-07-02 06:46:24.647 UTC
8
2022-01-17 23:42:28.157 UTC
2016-07-03 13:25:53.233 UTC
null
155,423
null
5,460,216
null
1
31
arrays|rust
8,535
<p>This is explained (along with the rest of the formatting syntax) in the <a href="http://doc.rust-lang.org/std/fmt/index.html"><code>std::fmt</code></a> documentation.</p> <p><code>{...}</code> surrounds all formatting directives. <code>:</code> separates the name or ordinal of the thing being formatted (which in this case is <em>omitted</em>, and thus means "the next thing") from the formatting options. The <code>?</code> is a formatting option that triggers the use of the <code>std::fmt::Debug</code> implementation of the thing being formatted, as opposed to the default <code>Display</code> trait, or one of the other traits (like <code>UpperHex</code> or <code>Octal</code>).</p> <p>Thus, <code>{:?}</code> formats the "next" value passed to a formatting macro, and supports anything that implements <code>Debug</code>.</p>
33,687,048
Email Template Design with Bootstrap
<p>I have to create a responsive email template design. I have been designing for a while, but never had a chance to create email templates.</p> <p>Can I use Bootstrap to create email templates, just like I would using a normal web-page with containers, rows and columns?</p> <p>If not, are there any specific tutorials, templates or considerations that I need to keep in mind?</p>
33,687,190
2
0
null
2015-11-13 06:25:28.2 UTC
4
2015-11-13 06:56:46.09 UTC
2015-11-13 06:56:46.09 UTC
null
5,239,503
null
2,561,623
null
1
7
html|twitter-bootstrap|email
48,279
<p>When u create an email Template, you must use inline styles with the template. Go through the following link. I think this will help you.</p> <p><a href="http://webdesign.tutsplus.com/articles/build-an-html-email-template-from-scratch--webdesign-12770" rel="noreferrer">http://webdesign.tutsplus.com/articles/build-an-html-email-template-from-scratch--webdesign-12770</a></p> <p><a href="http://webdesign.tutsplus.com/tutorials/creating-a-future-proof-responsive-email-without-media-queries--cms-23919" rel="noreferrer">http://webdesign.tutsplus.com/tutorials/creating-a-future-proof-responsive-email-without-media-queries--cms-23919</a></p>
20,145,140
How to use ETag in Web API using action filter along with HttpResponseMessage
<p>I have a ASP.Net Web API controller which simply returns the list of users.</p> <pre><code>public sealed class UserController : ApiController { [EnableTag] public HttpResponseMessage Get() { var userList= this.RetrieveUserList(); // This will return list of users this.responseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ObjectContent&lt;List&lt;UserViewModel&gt;&gt;(userList, new JsonMediaTypeFormatter()) }; return this.responseMessage; } } </code></pre> <p>and an action filter attribute class <code>EnableTag</code> which is responsible to manage ETag and cache:</p> <pre><code>public class EnableTag : System.Web.Http.Filters.ActionFilterAttribute { private static ConcurrentDictionary&lt;string, EntityTagHeaderValue&gt; etags = new ConcurrentDictionary&lt;string, EntityTagHeaderValue&gt;(); public override void OnActionExecuting(HttpActionContext context) { if (context != null) { var request = context.Request; if (request.Method == HttpMethod.Get) { var key = GetKey(request); ICollection&lt;EntityTagHeaderValue&gt; etagsFromClient = request.Headers.IfNoneMatch; if (etagsFromClient.Count &gt; 0) { EntityTagHeaderValue etag = null; if (etags.TryGetValue(key, out etag) &amp;&amp; etagsFromClient.Any(t =&gt; t.Tag == etag.Tag)) { context.Response = new HttpResponseMessage(HttpStatusCode.NotModified); SetCacheControl(context.Response); } } } } } public override void OnActionExecuted(HttpActionExecutedContext context) { var request = context.Request; var key = GetKey(request); EntityTagHeaderValue etag; if (!etags.TryGetValue(key, out etag) || request.Method == HttpMethod.Put || request.Method == HttpMethod.Post) { etag = new EntityTagHeaderValue("\"" + Guid.NewGuid().ToString() + "\""); etags.AddOrUpdate(key, etag, (k, val) =&gt; etag); } context.Response.Headers.ETag = etag; SetCacheControl(context.Response); } private static void SetCacheControl(HttpResponseMessage response) { response.Headers.CacheControl = new CacheControlHeaderValue() { MaxAge = TimeSpan.FromSeconds(60), MustRevalidate = true, Private = true }; } private static string GetKey(HttpRequestMessage request) { return request.RequestUri.ToString(); } } </code></pre> <p>The above code create an attribute class to manage ETag. So on the first request, it will create a new E-Tag and for the subsequent request it will check whether any ETag is existed. If so, it will generate <code>Not Modified</code> HTTP Status and return back to client. </p> <p>My problem is, I want to create a new ETag if there are changes in my user list, ex. a new user is added, or an existing user is deleted. and append it with the response. This can be tracked by the <code>userList</code> variable.</p> <p>Currently, the ETag received from client and server are same from every second request, so in this case it will always generate <code>Not Modified</code> status, while I want it when actually nothing changed. </p> <p>Can anyone guide me in this direction?</p>
47,547,988
5
0
null
2013-11-22 12:39:03.95 UTC
13
2019-11-05 10:21:03.887 UTC
2019-11-05 10:21:03.887 UTC
null
133
null
2,086,778
null
1
18
c#|asp.net-web-api
31,819
<p>My requirement was to cache my web api JSON responses... And all the solutions provided don't have an easy "link" to where the data is generated - ie in the Controller...</p> <p>So my solution was to create a wrapper "CacheableJsonResult" which generated a Response, and then added the ETag to the header. This allows a etag to be passed in when the controller method is generated and wants to return the content...</p> <pre><code>public class CacheableJsonResult&lt;T&gt; : JsonResult&lt;T&gt; { private readonly string _eTag; private const int MaxAge = 10; //10 seconds between requests so it doesn't even check the eTag! public CacheableJsonResult(T content, JsonSerializerSettings serializerSettings, Encoding encoding, HttpRequestMessage request, string eTag) :base(content, serializerSettings, encoding, request) { _eTag = eTag; } public override Task&lt;HttpResponseMessage&gt; ExecuteAsync(System.Threading.CancellationToken cancellationToken) { Task&lt;HttpResponseMessage&gt; response = base.ExecuteAsync(cancellationToken); return response.ContinueWith&lt;HttpResponseMessage&gt;((prior) =&gt; { HttpResponseMessage message = prior.Result; message.Headers.ETag = new EntityTagHeaderValue(String.Format("\"{0}\"", _eTag)); message.Headers.CacheControl = new CacheControlHeaderValue { Public = true, MaxAge = TimeSpan.FromSeconds(MaxAge) }; return message; }, cancellationToken); } } </code></pre> <p>And then, in your controller - return this object:</p> <pre><code>[HttpGet] [Route("results/{runId}")] public async Task&lt;IHttpActionResult&gt; GetRunResults(int runId) { //Is the current cache key in our cache? //Yes - return 304 //No - get data - and update CacheKeys string tag = GetETag(Request); string cacheTag = GetCacheTag("GetRunResults"); //you need to implement this map - or use Redis if multiple web servers if (tag == cacheTag ) return new StatusCodeResult(HttpStatusCode.NotModified, Request); //Build data, and update Cache... string newTag = "123"; //however you define this - I have a DB auto-inc ID on my messages //Call our new CacheableJsonResult - and assign the new cache tag return new CacheableJsonResult&lt;WebsiteRunResults&gt;(results, GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings, System.Text.UTF8Encoding.Default, Request, newTag); } } private static string GetETag(HttpRequestMessage request) { IEnumerable&lt;string&gt; values = null; if (request.Headers.TryGetValues("If-None-Match", out values)) return new EntityTagHeaderValue(values.FirstOrDefault()).Tag; return null; } </code></pre> <p>You need to define how granular to make your tags; my data is user-specific, so I include the UserId in the CacheKey (etag)</p>
36,725,181
Not compatible with your operating system or architecture: [email protected]
<p>I'm using Ubuntu 15.04. While running the following command:</p> <pre><code>npm install fsevents </code></pre> <p>I'm getting following error:</p> <pre><code>npm WARN optional Skipping failed optional dependency /chokidar/fsevents: npm WARN notsup Not compatible with your operating system or architecture: [email protected] npm WARN [email protected] No repository field. </code></pre> <p>Has anybody solved this?</p>
37,645,484
7
0
null
2016-04-19 17:16:31.933 UTC
14
2019-12-21 14:13:07.39 UTC
2018-10-25 16:05:30.06 UTC
null
5,490,782
null
4,768,375
null
1
78
javascript|node.js|npm|npm-install|fsevents
70,687
<p>I was facing the same issue with this dependecy when building other application.</p> <p>Just for the sake of knowledge and to people who are not well used to NPM, and thus uncertain about how their applications will behave: </p> <p>Since <code>fsevents</code> is an <em>API in OS X allows applications to register for notifications of changes to a given directory tree</em>. Running:</p> <p><code>npm install --no-optional</code></p> <p>Will do the trick, with no drawbacks.</p>
20,375,432
Decoupling ASP.NET MVC 5 Identity to allow implementing a layered application
<p>I'm new to ASP.NET MVC and I've been developing a MVC 5 application with individual user authentication. I've been doing a layered pattern when doing my applications like separating Model layer, DAL layer, Repos, etc. etc. but now in MVC 5, I want to be able to use the user and role management and authentication which they call Identity, and then still have that layered structure to my application because right now it seems Identity is pretty much coupled with the MVC project itself with the user and role models in there and the context too. </p> <p>What I did in my application for now is I have all my supposed-to-be-separate layers like my DAL, UnitOfWork, Repos, other models, etc in the MVC project (in separate folders!) just to make it work, for now. And I know it's just not the right way to do it.</p> <p>So can anyone point me to some good examples or articles about this or explain it directly if it's possible or not and how? Google hasn't been friendly to me about this one. Thanks!</p>
20,380,922
1
0
null
2013-12-04 12:29:45.623 UTC
30
2016-03-15 11:04:57.77 UTC
2013-12-04 12:45:37.707 UTC
null
1,476,249
null
1,476,249
null
1
44
c#|asp.net|asp.net-mvc|asp.net-mvc-5|asp.net-identity
11,278
<p>Here is a quick draft of what I'd try...I would create these layers:</p> <ul> <li>Contoso.Core (Class Library)</li> <li>Contoso.Data (Class Library)</li> <li>Contoso.Service (Class Library)</li> <li>Contoso.Web.Framework (Class Library)</li> <li>Contoso.Web (ASP.NET MVC 5.0)</li> </ul> <p><strong>Contoso.Core:</strong></p> <p>This layer holds all my entities/classes representing my database TABLES.</p> <p>So for example, I would have a:</p> <ul> <li>User.cs class.</li> <li>Product.cs class</li> <li>ProductDetail.cs class</li> <li>Etc..</li> </ul> <p>Some people call these entities/classes: the Domain Objects, others call it the POCO classes.</p> <p>Either or, these entities/classes are defined in the Core Layer since they may (or may not) be used amongst the other layers.</p> <hr> <p><strong>Contoso.Data:</strong></p> <p>This layer is where I define my <code>ContosoDbContext.cs</code> class. It is inside that file that I have all my <code>DbSet&lt;&gt;</code> defined. So for example, I would have the following inside my <code>ContosoDbContext.cs</code>:</p> <ul> <li>public DbSet User { get; set; }</li> <li>public DbSet Product { get; set; }</li> <li>public DbSet ProductDetail { get; set; }</li> </ul> <p>Needless to say, the Contoso.Data layer WILL HAVE A DEPENDECY on the <code>Contoso.Core</code> layer. In addition, it is inside that <code>Contoso.Data</code> layer that I would have my Generic Repository and anything related to "data access".</p> <hr> <p><strong>Contoso.Service:</strong></p> <p>This layer would be where I place all my business rules. For example, I may have a <code>UserService.cs</code> class that could have a <code>Login()</code> method. The Login() method would receive a username/password and call the Repository to lookup the user.</p> <p>Because the Service layer needs the Repository, I WILL HAVE A DEPENDENCY on the <code>Contoso.Data</code> layer AND because I'll be playing around with the User class (which happens to live inside the <code>Contoso.Core</code> layer), I WILL ALSO HAVE A DEPENDENCY on the <code>Contoso.Core</code> layer.</p> <hr> <p><strong>Contoso.Web.Framework:</strong></p> <p>This layer would have a dependency on the <code>Contoso.Core</code>, <code>Contoso.Data</code> and <code>Contoso.Service</code>. I would use this <code>Contoso.Web.Framework</code> layer to configure my Dependency Injection.</p> <hr> <p><strong>Contoso.Web:</strong></p> <p>The final layer, the MVC 5.0 application, would have a dependency on the <code>Contoso.Web.Framework</code> AND on the <code>Contoso.Service</code> AND on the <code>Contoso.Core</code> layers.</p> <p>The Controllers, would invoke methods living inside the classes defined in your <code>Contoso.Service</code> layer (for example the Login() method).</p> <p>The Login() method may or may not, for example, return a User class (null or populated) and because it returns a User class AND BECAUSE we are inside a Controller, our <code>Contoso.Web</code> layer needs a dependency on the <code>Contoso.Service</code> and <code>Contoso.Core</code>.</p> <hr> <p>Of course, I haven't detailed everything here or every layer but this is just to give you an example of the type of architecture I’d use.</p> <p>So far, I haven't answered your question but with little I know about MVC 5.0 and its new Identity mechanism, I believe the <code>Contoso.Core</code> layer would need to have a dependency on <code>Microsoft.AspNet.Identity.EntityFramework</code> in addition to the <code>Microsoft.AspNet.Identity.Core</code></p> <p>Likewise, my <code>ContosoDbContext.cs</code> class would need to implement the <code>IdentityDbContext</code> interface which happens to belong to the <code>Microsoft.AspNet.Identity.EntityFramework.dll</code>. </p> <p>This means my <code>Contoso.Data</code> layer would have a dependency on <code>Microsoft.AspNet.Identity.EntityFramework</code> and most probably the <code>Microsoft.AspNet.Identity.Core</code> as well...</p> <p>As you say, when you create a new MVC 5.0 project, all of this exist and is defined within the single application. Nothing is or has been decoupled into layers. So in the above architecture the <code>ContosoDbcontext.cs</code> class lives inside the <code>Contoso.Data</code> layer and NOT directly inside the ASP.NET MVC application.</p> <p>Since I haven't tried the new ASP.NET Identity nor have I tried to decouple things around, I wouldn't know how to honestly answer your question. I guess you'll have to try and move things around.</p> <p>If and when you do, feel free to tell us how it went and what are the things/problems you encountered.</p> <p>Meanwhile, I hope this has helped you shed some light (or not).</p> <p>Vince</p>
53,633,538
How to enable Nullable Reference Types feature of C# 8.0 for the whole project
<p>According to the <a href="https://youtu.be/VdC0aoa7ung?t=137" rel="noreferrer">C# 8 announcement video</a> the "nullable reference types" feature can be enabled for the whole project.</p> <p>But how to enable it for the project? I did not find any new appropriate option in the Project Properties window in Visual Studio 2019 Preview 1.</p> <p>Can it be enabled for 'legacy' <code>.csproj</code> projects if the C# language version is changed to 8.0?</p>
56,267,555
6
0
null
2018-12-05 13:33:03.6 UTC
15
2021-11-03 13:40:50.68 UTC
2019-10-31 02:04:15.827 UTC
null
397,817
null
2,660,553
null
1
128
c#|visual-studio|visual-studio-2019|c#-8.0|nullable-reference-types
72,144
<p>In Visual Studio 16.2 (from preview 1) the property name is changed to <code>Nullable</code>, which is simpler and aligns with the command line argument.</p> <p>Add the following properties to your <code>.csproj</code> file.</p> <pre class="lang-xml prettyprint-override"><code>&lt;PropertyGroup&gt; &lt;Nullable&gt;enable&lt;/Nullable&gt; &lt;LangVersion&gt;8.0&lt;/LangVersion&gt; &lt;/PropertyGroup&gt; </code></pre> <p>If you're targeting <code>netcoreapp3.0</code> or later, you don't need to specify a <code>LangVersion</code> to enable nullable reference types.</p> <hr /> <p>For older Visual Studio versions:</p> <ul> <li>From 16.0 preview 2 to 16.1, set <code>NullableContextOptions</code> to <code>enable</code>.</li> <li>In 16.0 preview 1, set <code>NullableReferenceTypes</code> to <code>true</code>.</li> </ul>
36,022,926
What do the --save flags do with npm install
<p>I see instructions to install a package with either</p> <pre><code>npm install &lt;package_name&gt; </code></pre> <p>or</p> <pre><code>npm install &lt;package_name&gt; --save </code></pre> <p>or</p> <pre><code>npm install &lt;package_name&gt; --save-dev </code></pre> <p>What is the difference between these options?</p>
36,023,013
3
0
null
2016-03-15 21:52:39.543 UTC
23
2021-01-21 16:05:29.683 UTC
2019-02-13 15:00:42.387 UTC
null
3,257,186
null
1,299,362
null
1
185
npm|npm-install
60,102
<p><code>npm install &lt;package_name&gt; --save</code> installs the package and updates the dependencies in your package.json. Since this question was asked there was a change to npm, such that <code>--save</code> has become the default option, so you do not need to use <code>--save</code> to update the dependencies.</p> <p><code>npm install &lt;package_name&gt; --no-save</code> installs the package but does not update the dependencies as listed in your package.json.</p> <p><code>npm install &lt;package_name&gt; ---save-dev</code> updates the <code>devDependencies</code> in your package. These are only used for local testing and development.</p> <p>You can read more at <a href="https://docs.npmjs.com/getting-started/using-a-package.json" rel="noreferrer">https://docs.npmjs.com/getting-started/using-a-package.json</a>.</p>
27,434,338
Laravel: Get pivot data for specific many to many relation
<p>My <code>User</code> model has many <code>Target</code> and vice versa. Now I've got a given <code>User</code> and given <code>Target</code> and I want to access pivot data from their relation. The pivot column is called <code>type</code></p> <p>How can I achieve this?</p>
27,434,970
3
0
null
2014-12-11 23:27:05.447 UTC
9
2022-06-19 20:14:40.243 UTC
2016-03-25 18:40:46.99 UTC
null
998,328
null
2,194,736
null
1
56
laravel|relationship
99,712
<p>On the relationships for both <code>User</code> and <code>Target</code>, tack on a <code>-&gt;withPivot('type')</code> which will instruct Laravel to include that column. Then once you have your result set, you can access the field with <code>$user-&gt;pivot-&gt;type</code>.</p> <p>If you're not iterating over a collection, but have a user and one of their targets and want the <code>type</code> field, you could use <code>$target = $user-&gt;targets-&gt;find($targetId)</code> and access the type with <code>$target-&gt;pivot-&gt;type</code>.</p> <p>More at <a href="http://laravel.com/docs/4.2/eloquent#working-with-pivot-tables">http://laravel.com/docs/4.2/eloquent#working-with-pivot-tables</a></p>
20,908,895
Could not load file or assembly 'WebGrease' one of its dependencies. The located assembly's manifest definition does not match the assembly reference
<p><strong>This issue has many solutions, please read all answers below, they might help you solve your problem too. If you find a new way to solve this, please document in your answer</strong> </p> <p>I am trying to add System.Web.Optimization to my ASP.NET Web Forms solution. I added Microsoft ASP.NET Web Optimization Framework through NuGet Packages. It added Microsoft.Web.Infrastracture and WebGrease (1.5.2) to the references.</p> <p>However, when I run </p> <pre><code>&lt;%= System.Web.Optimization.Scripts.Render("~/bundles/js")%&gt; </code></pre> <p>I get runtime error</p> <pre><code>Could not load file or assembly 'WebGrease, Version=1.5.1.25624, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) </code></pre> <p>I have tried adding assemblyBinding to the Web.Config</p> <pre><code>&lt;runtime&gt; &lt;legacyUnhandledExceptionPolicy enabled="1"/&gt; &lt;assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral"/&gt; &lt;bindingRedirect oldVersion="0.0.0.0-1.5.1.25624" newVersion="1.5.2.14234"/&gt; &lt;/dependentAssembly&gt; &lt;/assemblyBinding&gt; &lt;/runtime&gt; </code></pre> <p>But without any luck.</p> <p>I noticed that my WebSite's Web config contains this line</p> <pre><code> &lt;configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"&gt; </code></pre> <p>If I replace it with </p> <pre><code> &lt;configuration&gt; </code></pre> <p>Then everything works and I don't get the runtime error. Unfortunately, I need the xmlns. Other components of my project depend on it.</p> <p>Why would Optimization try to load an older version when schema is pointing to v2.0? Is there a way to force it to load the latest or the only available WebGrease.dll?</p> <p>What else can I try without changing the</p> <pre><code> &lt;configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"&gt; ? </code></pre> <p>Thank you for any help you can provide!</p> <p>Edit: 1) Attaching FusionLog Result. Maybe it will be helpful</p> <pre><code>=== Pre-bind state information === LOG: User = [USER] LOG: DisplayName = WebGrease, Version=1.5.1.25624, Culture=neutral, PublicKeyToken=31bf3856ad364e35 (Fully-specified) LOG: Appbase = file:///C:/Projects/PROJECT_NAME/trunk/www.PROJECT_NAME.com/ LOG: Initial PrivatePath = C:\Projects\PROJECT_NAME\trunk\www.PROJECT_NAME.com\bin Calling assembly : System.Web.Optimization, Version=1.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35. === LOG: This bind starts in default load context. LOG: Using application configuration file: C:\Projects\PROJECT_NAME\trunk\www.PROJECT_NAME.com\web.config LOG: Using host configuration file: LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config. LOG: Post-policy reference: WebGrease, Version=1.5.1.25624, Culture=neutral, PublicKeyToken=31bf3856ad364e35 </code></pre> <p>2) Confirmed, The issue is in </p> <pre><code>&lt;configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"&gt; </code></pre> <p>However, I don't understand why </p>
21,099,471
8
0
null
2014-01-03 17:02:04.367 UTC
2
2019-12-31 21:05:27.04 UTC
2018-01-22 19:06:23.153 UTC
null
3,158,020
null
3,158,020
null
1
20
c#|asp.net|asp.net-mvc|bundling-and-minification|asp.net-optimization
41,614
<p>Finally, the issue was in <code>&lt;configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"&gt;</code>. It caused the Render method to load wrong WebGrease assembly.</p> <p>Removing the xmlns solved the issue for me.</p>
22,908,204
How to make JSON.NET StringEnumConverter use hyphen-separated casing
<p>I consume an API which returns the string values like this:</p> <blockquote> <p><code>some-enum-value</code></p> </blockquote> <p>I try to put these values in an <code>enum</code> , since the default <code>StringEnumConverter</code> doesn't do what I want, which is to to decorate this Converter with some additional logic.</p> <p>How can I be sure that the values are <em>deserialized</em> correctly ?</p> <p>The following code is my tryout to get this job done. <br> However the line</p> <blockquote> <p><code>reader = new JsonTextReader(new StringReader(cleaned));</code></p> </blockquote> <p>breaks the whole thing since the <code>base.ReadJson</code> can't recognize the string as a JSON.</p> <p>Is there a better way to do this without having to implement all the existing logic in a <code>StringEnumConverter</code>? <br> How could I fix my approach?</p> <pre><code>public class BkStringEnumConverter : StringEnumConverter { public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.String) { var enumString = reader.Value.ToString(); if (enumString.Contains(&quot;-&quot;)) { var cleaned = enumString.Split('-').Select(FirstToUpper).Aggregate((a, b) =&gt; a + b); reader = new JsonTextReader(new StringReader(cleaned)); } } return base.ReadJson(reader, objectType, existingValue, serializer); } private static string FirstToUpper(string input) { var firstLetter = input.ToCharArray().First().ToString().ToUpper(); return string.IsNullOrEmpty(input) ? input : firstLetter + string.Join(&quot;&quot;, input.ToCharArray().Skip(1)); } } </code></pre>
22,938,928
4
0
null
2014-04-07 09:15:43.267 UTC
9
2021-01-07 10:53:24.323 UTC
2021-01-07 10:53:24.323 UTC
null
-1
null
624,395
null
1
51
c#|json|enums|json.net
61,348
<p>I solved the issue by adding EnumMember attributes on my enum values. The Json.NET default <code>StringEnumConverter</code> perfectly deals with these attributes.</p> <p>Example:</p> <pre><code>public enum MyEnum { [EnumMember(Value = "some-enum-value")] SomeEnumValue, Value, [EnumMember(Value = "some-other-value")] SomeOtherValue } </code></pre> <p>Please note that you only have to specify the attributes in case of dashes or other special chars you can't use in your enum. The uppercase lowercase is dealt with by the <code>StringEnumConverter</code>. So if the service returns a value like <code>someenumvalue</code> you should use it like this in the enum <code>Someenumvalue</code>. If you prefer <code>SomeEnumValue</code> you should use the <code>EnumMember</code> attribute. In case the service returns it like this <code>someEnumValue</code> you can just use it like this <code>SomeEnumValue</code> (It works out of the box when you use the CamelCaseText property). </p> <p>You can easily specify your converters and other settings in the <code>JsonSerializerSettings</code>.</p> <p>Here is an example of the settings I use myself.</p> <pre><code>new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), Converters = new List&lt;JsonConverter&gt; { new StringEnumConverter { CamelCaseText = true } }, NullValueHandling = NullValueHandling.Ignore }; </code></pre>
45,835,797
How do I create a webhook?
<p>So I am creating a click2call app, using Tropo and Nexmo, and at this point, I need help setting a webhook. They both provide a place to point a webhook, but now, I don't understand what to include there. Is it a php file? or a json? I've already tried to create a php and had the following: </p> <pre><code>&lt;?php header('Content-Type: application/json'); ob_start(); $json = file_get_contents('php://input'); $request = json_decode($json, true); $action = $request["result"]["action"]; $parameters = $request["result"]["parameters"]; $output["contextOut"] = array(array("name" =&gt; "$next-context", "parameters" =&gt; array("param1" =&gt; $param1value, "param2" =&gt; $param2value))); $output["speech"] = $outputtext; $output["displayText"] = $outputtext; $output["source"] = "whatever.php"; ob_end_clean(); echo json_encode($output); ?&gt; </code></pre> <p>how can I later retrieve the information from my webhook and store it in a DB? I've seen pieces of code, but I have no idea where to include it... is it in my api, in the php file that my webhook points?? Thank you in advance.</p>
45,844,612
2
0
null
2017-08-23 09:27:24.2 UTC
9
2022-06-22 09:14:58.23 UTC
2017-08-23 13:21:57.54 UTC
null
5,235,574
null
8,461,705
null
1
15
php|webhooks
39,859
<p>So I figured it out, in a very simple way. Just point your webhook to a php with the following code:</p> <pre><code>&lt;?php // Original Answer header('Content-Type: application/json'); $request = file_get_contents('php://input'); $req_dump = print_r( $request, true ); $fp = file_put_contents( 'request.log', $req_dump ); // Updated Answer if($json = json_decode(file_get_contents(&quot;php://input&quot;), true)){ $data = $json; } print_r($data); ?&gt; </code></pre> <p>And the information will be posted and then acessible through the 'request.log'</p> <p>Hope it can help others in the future.</p>
22,271,779
is it possible to use Gson.fromJson() to get ArrayList<ArrayList<String>>?
<p>let's say i have a <code>json</code> array of arrays</p> <pre><code>String jsonString = [["John","25"],["Peter","37"]]; </code></pre> <p>i would like to parst this into <code>ArrayList&lt;ArrayList&lt;String&gt;&gt;</code> objects. when i used</p> <p><code>Gson.fromJson(jsonString,ArrayList&lt;ArrayList&lt;String&gt;&gt;.class)</code></p> <p>it doesn't seem to work and i did a work around by using</p> <p><code>Gson.fromJson(jsonString,String[][].class)</code></p> <p>is there a better way to do this?</p>
22,271,806
1
0
null
2014-03-08 16:15:44.473 UTC
9
2014-03-08 16:39:45.21 UTC
2014-03-08 16:26:08.02 UTC
null
697,449
null
2,416,313
null
1
30
java|generics|arraylist|gson
37,141
<p>Yes, use a <a href="http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/reflect/TypeToken.html"><code>TypeToken</code></a>.</p> <pre><code>ArrayList&lt;ArrayList&lt;String&gt;&gt; list = gson.fromJson(jsonString, new TypeToken&lt;ArrayList&lt;ArrayList&lt;String&gt;&gt;&gt;() {}.getType()); </code></pre> <p>The <code>TypeToken</code> allows you to specify the generic type you actually want, which helps Gson find the types to use during deserialization.</p> <p>It uses this gem: <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getGenericSuperclass%28%29"><code>Class#getGenericSuperClass()</code></a>. The fact that it is an anonymous class makes it a sub class of <code>TypeToken&lt;...&gt;</code>. It's equivalent to a class like</p> <pre><code>class Anonymous extends TypeToken&lt;...&gt; </code></pre> <p>The specification of the method states that </p> <blockquote> <p>If the superclass is a parameterized type, the <code>Type</code> object returned must accurately reflect the actual type parameters used in the source code.</p> </blockquote> <p>If you specified</p> <pre><code>new TypeToken&lt;String&gt;(){}.getType(); </code></pre> <p>the <code>Type</code> object returned would actually be a <code>ParameterizedType</code> on which you can retrieve the actual type arguments with <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/ParameterizedType.html#getActualTypeArguments%28%29"><code>ParameterizedType#getActualTypeArguments()</code></a>.</p> <p>The type argument would be the <code>Type</code> object for <code>java.lang.String</code> in the example above. In your example, it would be a corresponding <code>Type</code> object for <code>ArrayList&lt;ArrayList&lt;String&gt;&gt;</code>. Gson would keep going down the chain until it built the full map of types it needs.</p>
27,918,305
Mocking framework for asp.net core 5.0
<p>I recently installed Visual Studio 2015 and started a project with a web site and a asp class library which will contain the unit tests for the web site. I usually use Moq for mocking but I am no stranger to try a different mocking framework. The problem I am having is that I added Moq as a reference to the unit test project and started using it. Everything seems fine at first until I tried to compile.</p> <p>When I compiled I got an error message saying:</p> <p><code>ASP.NET Core 5.0 error CS0246: The type or namespace name 'Moq' could not be found (are you missing a using directive or an assembly reference?)</code></p> <p>I noticed that I could switch between ASP.NET 5.0 and ASP.NET Core 5.0 in the code view and when selecting ASP.NET Core 5.0 I get errors but no when selecting ASP.NET 5.0. I tried searching for an answer but I did not have any luck.</p> <p>Is the problem that Moq does not work with vnext and I should use a different framework (if so which works?) or can I solve this somehow? My project.json:</p> <pre><code>{ "version": "1.0.0-*", "dependencies": { "Web": "1.0.0-*", "Xunit.KRunner": "1.0.0-beta1", "xunit": "2.0.0-beta5-build2785", "Moq": "4.2.1409.1722" }, "frameworks": { "aspnet50": { "dependencies": { } }, "aspnetcore50": { "dependencies": { } } }, "commands": { "test": "Xunit.KRunner" } } </code></pre>
27,918,571
4
0
null
2015-01-13 09:02:13.213 UTC
3
2016-10-15 06:19:56.297 UTC
2015-02-10 10:40:03.133 UTC
null
19,635
null
1,842,278
null
1
28
c#|asp.net|moq|asp.net-core
8,843
<p>I suppose that so far a version of Moq that works with asp.net core 5.0 is not available in the nuget feed, but I think you can work with Asp.Net 5.0.</p>
27,940,480
Rename Google Compute Engine VM Instance
<p>How do I rename a Google Compute Engine VM instance? </p> <p>I created a new LAMP server and I'd like to rename it in the "VM Instances" dashboard.</p> <p>I've tried renaming the Custom metadata, but that didn't seem to replicate to the dashboard.</p>
27,964,746
12
0
null
2015-01-14 10:15:09.143 UTC
6
2022-09-08 18:46:14.207 UTC
2015-01-24 20:54:02.093 UTC
null
3,618,671
null
4,160,138
null
1
39
virtual-machine|google-compute-engine|hostname
38,558
<p>Another way to do this is:</p> <ul> <li>snapshot the disk of the existing instance</li> <li>create a new disk from that snapshot</li> <li>create a new instance with that disk and give it the name you would like</li> </ul> <p>It sounds time-consuming, but in reality should take 5 minutes.</p>
29,595,391
How to implement pagination on a custom WP_Query Ajax
<p>I want to paginate my WordPress posts in a custom loop with Ajax, so when I click on load more button posts will appear.</p> <p>My code:</p> <pre><code>&lt;?php $postsPerPage = 3; $args = array( 'post_type' =&gt; 'post', 'posts_per_page' =&gt; $postsPerPage, 'cat' =&gt; 1 ); $loop = new WP_Query($args); while ($loop-&gt;have_posts()) : $loop-&gt;the_post(); ?&gt; &lt;h1&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt; &lt;p&gt; &lt;?php the_content(); ?&gt; &lt;/p&gt; &lt;?php endwhile; echo '&lt;a href="#"&gt;Load More&lt;/a&gt;'; wp_reset_postdata(); ?&gt; </code></pre> <p>This code does not paginate. Is there a better way to do this?</p>
29,595,780
1
0
null
2015-04-12 22:28:53.487 UTC
12
2015-04-20 12:52:05.37 UTC
2015-04-15 06:11:05.193 UTC
null
4,186,297
null
4,780,700
null
1
4
php|jquery|ajax|wordpress|pagination
27,525
<p>The <code>Load More</code> button needs to send a <code>ajax</code> request to the server and the returned data can be added to the existent content using jQuery or plain javascript. Assuming your using jQuery this would starter code.</p> <p><strong>Custom Ajax Handler (Client-side)</strong></p> <pre><code>&lt;a href="#"&gt;Load More&lt;/a&gt; </code></pre> <p>Change to:</p> <pre><code>&lt;a id="more_posts" href="#"&gt;Load More&lt;/a&gt; </code></pre> <p><em>Javascript:</em> - Put this at the bottom of the file.</p> <pre><code>//&lt;/script type="text/javascript"&gt; var ajaxUrl = "&lt;?php echo admin_url('admin-ajax.php')?&gt;"; var page = 1; // What page we are on. var ppp = 3; // Post per page $("#more_posts").on("click",function(){ // When btn is pressed. $("#more_posts").attr("disabled",true); // Disable the button, temp. $.post(ajaxUrl, { action:"more_post_ajax", offset: (page * ppp) + 1, ppp: ppp }).success(function(posts){ page++; $(".name_of_posts_class").append(posts); // CHANGE THIS! $("#more_posts").attr("disabled",false); }); }); //&lt;/script&gt; </code></pre> <p><strong>Custom Ajax Handler (Server-side)</strong> <em>PHP</em> - Put this in the functions.php file.</p> <pre><code>function more_post_ajax(){ $offset = $_POST["offset"]; $ppp = $_POST["ppp"]; header("Content-Type: text/html"); $args = array( 'post_type' =&gt; 'post', 'posts_per_page' =&gt; $ppp, 'cat' =&gt; 1, 'offset' =&gt; $offset, ); $loop = new WP_Query($args); while ($loop-&gt;have_posts()) { $loop-&gt;the_post(); the_content(); } exit; } add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax'); add_action('wp_ajax_more_post_ajax', 'more_post_ajax'); </code></pre>
45,337,959
does angular material have a grid system?
<p>I'm starting a project with angular material. Does it have a native system for positioning elements in a responive grid like bootstrap does ?</p> <p>Otherwise is it ok practice to combine material design with bootstrap for the grid system ?</p> <p>Maybe I am taking the wrong aproach to the problem.</p>
45,353,318
4
2
null
2017-07-26 21:43:56.177 UTC
6
2021-09-15 14:00:31.923 UTC
2017-07-27 14:11:28.38 UTC
null
5,556,177
null
6,797,267
null
1
28
css|twitter-bootstrap|material-design|angular-material2
21,049
<p>If you are using Material2, you can use <a href="https://github.com/angular/flex-layout/wiki/API-Documentation" rel="noreferrer">Angular Flex Layout</a> for responsiveness. It compliments Angular2 well and is lightweight. </p> <p>Basically Material2 + Flex-layout is equivalent to Bootsrap library.</p> <p>Here's an <a href="https://plnkr.co/edit/a4iASMaZqQZNmuuQUapb?p=preview" rel="noreferrer">example</a> of how flex-layout can be used for grid system/responsiveness with Angular/Material2.</p> <p>Sample Code showing use of flex-layout API:</p> <pre><code>&lt;div fxShow.xs="true" fxShow="false" &gt;Screen size &lt;h1&gt;XS&lt;/h1&gt;&lt;/div&gt; &lt;div fxShow.sm="true" fxShow="false" &gt;Screen size &lt;h1&gt;SM&lt;/h1&gt;&lt;/div&gt; &lt;div fxShow.md="true" fxShow="false" &gt;Screen size &lt;h1&gt;MD&lt;/h1&gt;&lt;/div&gt; &lt;div fxShow.lg="true" fxShow="false" &gt;Screen size &lt;h1&gt;LG&lt;/h1&gt;&lt;/div&gt; &lt;div fxShow.xl="true" fxShow="false" &gt;Screen size &lt;h1&gt;XL&lt;/h1&gt;&lt;/div&gt; &lt;div fxLayout="row" fxLayout.xs="column" fxLayoutGap="10px" fxLayoutAlign.xs="center center" fxLayoutWrap&gt; &lt;div class="sample-div" fxFlexOrder.lt-md="7"&gt;Div 1&lt;/div&gt; &lt;div class="sample-div" fxFlexOrder.lt-md="6"&gt;Div 2&lt;/div&gt; &lt;div class="sample-div" fxFlexOrder.lt-md="5"&gt;Div 3&lt;/div&gt; &lt;div class="sample-div" fxFlexOrder.lt-md="4"&gt;Div 4&lt;/div&gt; &lt;div class="sample-div" fxFlexOrder.lt-md="3"&gt;Div 5&lt;/div&gt; &lt;div class="sample-div" fxFlexOrder.lt-md="2"&gt;Div 6&lt;/div&gt; &lt;div class="sample-div" fxFlexOrder.lt-md="1"&gt;Div 7&lt;/div&gt; &lt;div class="sample-div" fxFlexOrder.lt-md="0"&gt;Div 8&lt;/div&gt; &lt;/div&gt; </code></pre>
23,542,453
Change backslash to forward slash in windows batch file
<p>I'm trying to convert all backslashes () to forward slashes (/) in a variable which contains a file name and location. I've read about this and seen:</p> <pre><code>%variable:str1=str2% </code></pre> <p>and</p> <pre><code>set "var=%var:\=/%" </code></pre> <p>which I've attempted, but I'm obviously not getting it right.</p> <p>Here is the relevant section of my .bat script:</p> <pre><code>FOR %%f IN ("E:\myfiles\app1\data\*.csv") DO ( echo %%f set "f=%%f:\=/%" echo %%f echo. ) </code></pre> <p>The output show each filename listed twice. </p> <p>i.e. this line:</p> <pre><code>set "f=f:\=/%" </code></pre> <p>is not doing what I want it to. Can anyone see what I am doing wrong?</p>
23,544,690
5
1
null
2014-05-08 12:58:15.807 UTC
14
2020-06-11 17:14:24.483 UTC
2014-05-08 13:25:15.587 UTC
null
463,115
null
3,253,319
null
1
44
windows|string|batch-file|slash
49,001
<p>Within a block statement <code>(a parenthesised series of statements)</code>, the <strong>entire</strong> block is parsed and <strong>then</strong> executed. Any <code>%var%</code> within the block will be replaced by that variable's value <strong>at the time the block is parsed</strong> - before the block is executed - the same thing applies to a <code>FOR ... DO (block)</code>.</p> <p>Hence, <code>IF (something) else (somethingelse)</code> will be executed using the values of <code>%variables%</code> at the time the <code>IF</code> is encountered.</p> <p>Two common ways to overcome this are 1) to use <code>setlocal enabledelayedexpansion</code> and use <code>!var!</code> in place of <code>%var%</code> to access the changed value of <code>var</code> or 2) to call a subroutine to perform further processing using the changed values.</p> <p>Note therefore the use of <code>CALL ECHO %%var%%</code> which displays the changed value of <code>var</code>.</p> <p>Your code contains two separate variables called <code>f</code>.</p> <p>The first is the loop-control 'metavariable' called <code>f</code> and referenced by <code>%%f</code>.</p> <p>The second is the common environment variable <code>f</code> which is established by the <code>set "f=..."</code> statement. This variable can be accessed by using <code>%f%</code> <strong>but</strong> within a <code>block</code>, it will appear to retain the value it had when the controlling <code>for</code> was parsed (in fact, any <code>%var%</code> is replaced at parse-time by the value of <code>var</code> <strong>at that time</strong>)</p> <p><code>metavariables</code> cannot be used in string-manipulation statements like substrings or substitutes, only common environment variables can be used for these operations, hence you need to assign the value of the metavariable <code>f</code> to the environment variable <code>f</code> and <em>then</em> perform the string-substitution task of the environment variable <code>f</code>.</p> <p>The twist, of course, is that you must use <code>delayedexpansion</code> and the <code>!var!</code> syntax to access the modified value of an environment variable within a block.</p> <p>So,</p> <pre><code>setlocal enabledelayedexpansion for...%%f...do ( echo %%f set "f=%%f" set "f=!f:\=/!" echo !f! ) echo just for demonstration %f% !f! %%f </code></pre> <p>This sets the value of <code>f</code> in the required manner (of course, you could always change the name to avoid confusion...)</p> <p>The last line is simply to show that the final value acquired by <code>f</code> can be accessed outside of the loop as either <code>%f%</code> or <code>!f!</code>, and that <code>%%f</code> is out-of-context and shown as <code>%f</code>.</p> <p>Another way to do this without <code>delayedexpansion</code> is</p> <pre><code>for...%%f...do ( echo %%f set "f=%%f" call set "f=%%f:\=/%%" call echo %%f%% ) echo just for demonstration %f% !f! %%f </code></pre> <p>the difference being the use of <code>call</code> and doubling the <code>%</code>s, and the final line will show <code>!f!</code> as just that - a literal, since outside of <code>delayedexpansion</code> mode, <code>!</code> is just another character with no special meaning to <code>cmd</code>.</p>
42,620,847
Is there a React shorthand for passing props?
<p>I am tired of doing this all the time:</p> <pre><code>&lt;Elem x={x} y={y} z={z} /&gt; &lt;Elem x={this.props.x} y={this.props.y} z={this.props.z} /&gt; </code></pre> <p>Is there a way I can get something like this to work?</p> <pre><code>&lt;Elem x, y, z /&gt; </code></pre> <p>or</p> <pre><code>&lt;Elem {x, y, z} /&gt; </code></pre>
42,622,168
3
5
null
2017-03-06 08:31:01.853 UTC
2
2022-04-16 20:08:34.997 UTC
2022-02-13 16:28:12.84 UTC
null
3,257,186
null
644,891
null
1
34
reactjs
16,143
<p>As specified in the comments , you should use a <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator" rel="noreferrer">spread operator</a> as a shorthand of sending multiple arguments to the component.</p> <p><code>&lt;Elem {...this.props} /&gt;</code></p> <p>If the Elem component is a stateless component , you should be able to access the props just like any argument passed on the component. You probably dont need to use the <code>this.props</code> keyword in that case.</p>
25,596,284
SDK Location not found in android studio
<p>I have just imported my eclipse project in android studio. it keeps my saying that</p> <pre><code>Error:SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable. </code></pre> <p>I have seen some tutorials of editing local.properties files but it didnt work. here is my project.properties file:</p> <pre><code>sdk.dir=E:\\Mod Eclipse\\adt-bundle-windows-x86_64-20130219\\sdk </code></pre> <p>Actual directory of my folder is :</p> <p><strong>E:\Mod Eclipse\adt-bundle-windows-x86_64-20130219\sdk</strong></p>
25,596,388
13
1
null
2014-08-31 21:03:53.093 UTC
8
2022-07-08 17:46:36.623 UTC
2014-08-31 21:09:15.64 UTC
null
3,418,888
null
3,418,888
null
1
39
android|android-studio
107,714
<p>You should also change it on Project Structure. </p> <ul> <li><p>Close the current project and you'll see pop up with dialog which will then proceed to Configure option.</p> <p>Configure -> Project Defaults -> Project Structure -> SDKs on left column -> Android SDK Home Path -> give the exact path as you did on local.properties and select Valid Target.</p></li> </ul> <p>There you go.</p>
32,253,935
Remove leading zero in Java
<pre><code>public static String removeLeadingZeroes(String value): </code></pre> <p>Given a valid, non-empty input, the method should return the input with all leading zeroes removed. Thus, if the input is “0003605”, the method should return “3605”. As a special case, when the input contains only zeroes (such as “000” or “0000000”), the method should return “0”</p> <pre><code>public class NumberSystemService { /** * * Precondition: value is purely numeric * @param value * @return the value with leading zeroes removed. * Should return "0" for input being "" or containing all zeroes */ public static String removeLeadingZeroes(String value) { while (value.indexOf("0")==0) value = value.substring(1); return value; } </code></pre> <p>I don't know how to write codes for a string "0000".</p>
32,254,059
14
2
null
2015-08-27 15:43:58.677 UTC
2
2021-08-11 15:15:59.03 UTC
2015-08-27 16:58:14.473 UTC
null
472,495
null
5,273,624
null
1
13
java|string
50,885
<p>I would consider checking for that case first. Loop through the string character by character checking for a non "0" character. If you see a non "0" character use the process you have. If you don't, return "0". Here's how I would do it (untested, but close)</p> <pre><code>boolean allZero = true; for (int i=0;i&lt;value.length() &amp;&amp; allZero;i++) { if (value.charAt(i)!='0') allZero = false; } if (allZero) return "0" ...The code you already have </code></pre>
32,152,233
Getting the range of data from a list in Python
<p>I have a set of data that is in a list. I am not sure how to make a function which can take the range of that data and return the min and max values in a tuple. </p> <p>data:</p> <pre><code>[1,3,4,463,2,3,6,8,9,4,254,6,72] </code></pre> <p>my code at the moment:</p> <pre><code>def getrange(data): result=[] if i,c in data: range1 = min(data) range2 = max(data) result.append(range1, range2) return result </code></pre>
32,152,284
4
4
null
2015-08-22 04:15:37.867 UTC
null
2020-05-26 16:37:37.263 UTC
2015-08-22 05:10:08.02 UTC
null
5,234,557
null
5,234,557
null
1
4
python|list|range|max|min
52,680
<p>This is a very straight forward question and you're very close. If what I have below isn't correct, then please edit your question to reflect what you would like.</p> <p>Try this.</p> <pre><code>def minmax(val_list): min_val = min(val_list) max_val = max(val_list) return (min_val, max_val) </code></pre> <hr> <p><strong>Semantics</strong></p> <blockquote> <p>I have a set of data that is in a list.</p> </blockquote> <p>Be careful here, you're using python terms in a contradictory manner. In python, there are both sets and lists. I could tell you meant list here but you could confuse people in the future. Remember, in python sets, tuples, and lists are all different from one another.</p> <p>Here are the differences (taken from BlackJack's comment below)</p> <pre><code>Data Type | Immutable | Ordered | Unique Values =============================================== lists | no | yes | no tuples | yes | yes | no sets | no | no | yes </code></pre> <p>Immutable - the data type can't be changed after instantiation.</p> <p>Ordered - the order of the elements within the data type are persistent.</p> <p>Unique Values - the data type cannot have repeated values.</p>
4,160,746
Creating Dependency Graphs in Python
<p>I have inherited a huge codebase that I need to make some small changes into. I was wondering if there are utilities that would parse python code and give dependencies between functions, as in if I make changes to a function I want to be sure that I dont break other functions, so if I could see in a graph like diagram it would make my life easier.</p>
4,160,800
1
1
null
2010-11-12 01:00:44.727 UTC
25
2019-11-29 05:31:35.373 UTC
2010-11-15 02:11:14.78 UTC
null
18,243
null
225,260
null
1
34
python|dependency-management|call-flow
16,481
<ul> <li>Usually "dependency" is defined for module / package import.</li> <li><p>What you are looking for is a visualizing call flow.</p> <ul> <li><a href="http://pycallgraph.slowchop.com/" rel="noreferrer">http://pycallgraph.slowchop.com/</a></li> </ul></li> <li><p>You can still not guarantee that you will not break functionality :)</p></li> <li><p>My experience and solution:</p> <p>Many a times, I found the call flow data overwhelming and the diagram too complex. So what i usually do is trace call flow partially for the function, I am interested in.</p> <p>This is done by utilizing the sys.settrace(...) function. After generating the call flows as textual data, I generate a call graph using graphviz.</p> <ul> <li><a href="http://docs.python.org/library/sys.html" rel="noreferrer">http://docs.python.org/library/sys.html</a></li> <li><a href="http://pyfunc.blogspot.com/2010/10/tracing-callflows-in-python.html" rel="noreferrer">On call tracing</a></li> <li>For generating graphs, use graphviz solutions from <a href="http://networkx.lanl.gov/pygraphviz/" rel="noreferrer">networkX</a>.</li> </ul></li> </ul> <p>[Edit: based on comments]</p> <p>Then my piecemeal solution works better. Just insert the code and use the decorator on a function that you want to trace. You will see gaps where deferred comes into picture but that can be worked out. You will not get the complete picture directly. </p> <p>I have been trying to do that and made a <a href="http://pyfunc.blogspot.com/search/label/Twisted" rel="noreferrer">few post</a> that works on that understanding. </p>
39,819,441
Keeping a fork up to date
<p>I wanted to commit somthing to a github repository, but I (obviously) didn't have any rights to do so. I made a fork of that repo, commited my changes and submitted a pull-request. Now, the problem is that after a while other people have made commits to the original repo, which means my fork is no longer up-to-date.</p> <p>How should now update my fork? Is this (<a href="https://stackoverflow.com/a/23853061/5513628">https://stackoverflow.com/a/23853061/5513628</a>) still a valid way or do I have to delete my repo and make a new fork every time?</p> <p>This is what the fork looks like in github desktop:</p> <p><a href="https://i.stack.imgur.com/R0hDS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/R0hDS.png" alt="enter image description here"></a></p> <p>The pull request was made by me but the two commits after that were made by other people. They are not contained in my repo...</p>
39,822,102
4
2
null
2016-10-02 17:01:21.49 UTC
24
2021-09-15 13:43:29.747 UTC
2017-05-23 12:10:02.173 UTC
null
-1
null
5,513,628
null
1
33
github
16,677
<p>To sync changes you make in a fork with the original repository, you must configure a remote that points to the upstream repository in Git.</p> <p>Specify a new remote upstream repository that will be synced with the fork.</p> <pre><code>git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git </code></pre> <p>You can check if it was succesful with:</p> <pre><code>git remote -v </code></pre> <p>Then fetch it to update your project:</p> <pre><code>git fetch upstream </code></pre> <p>Merge the changes from upstream/master into your local master branch.</p> <pre><code>git merge upstream/master </code></pre> <p>At last, you can commit new update from original repository to your fork repository.</p> <p><strong>Shortcut</strong>: you can also combine the last two commands into a single command:</p> <pre><code>git fetch upstream git merge upstream/master </code></pre> <p>Is equal to:</p> <pre><code>git pull upstream/master </code></pre> <p>This information can also be found on GitHub <a href="https://help.github.com/articles/configuring-a-remote-for-a-fork/" rel="noreferrer">here</a> and <a href="https://help.github.com/articles/syncing-a-fork/" rel="noreferrer">here</a>.</p>
38,985,421
Variable in for loop is a string
<p>I'm not sure if this is normal behavior, but running this:</p> <pre><code>for (var i in [1, 2, 3]) { console.log(i + 1); } </code></pre> <p>Results in this:</p> <pre><code>// 01 // 11 // 21 </code></pre> <p>Could somebody please explain, why is <code>var i</code> being treated like a string in this situation and not if I do <code>for (var i = 0; i &lt; [1, 2, 3].length; i++)</code>?</p>
38,985,456
8
5
null
2016-08-16 22:23:20.853 UTC
3
2021-12-28 22:55:35.163 UTC
2016-08-16 22:27:32.267 UTC
null
2,129,254
null
2,129,254
null
1
33
javascript|for-loop
5,988
<p>Its most likely because in this for loop style (for..in), it is treating <code>i</code> as a key, and since keys in objects are usually strings (yes, an array is a type of object in javascript), it is treating it as a String. </p> <p><code>parseInt(i)</code> works in this situation, but for good programming practice, you would want to use a <code>for</code> loop that looks similar to this:</p> <pre><code>var array = [1, 2, 3]; for (var i = array.length - 1; i &gt;= 0; i--) { // do work with each array element here } </code></pre>
26,623,980
User Authentication with Grape and Devise
<p>I have difficulties to understand and also properly implement <strong><em>User Authentication</em></strong> in APIs. In other words, I have serious problem to understand the integration of Grape API with front-end frameworks such as Backbone.js, AngularJS or Ember.js. </p> <p>I'm trying to pivot all different approaches and read a lot about that, but Google returns me truly bad resources and it seems to me, like there is no really good article on this topic - <em>Rails and User authentication with Devise and front-end frameworks</em>.</p> <p>I will describe my current pivot and I hope you can provide me some feedback on my implementation and maybe point me to the right direction.</p> <p><strong>Current implementation</strong></p> <p>I have backend <strong>Rails REST API</strong> with following <strong><em>Gemfile</em></strong>(I will purposely shorten all file code)</p> <pre><code>gem 'rails', '4.1.6' gem 'mongoid', '~&gt; 4.0.0' gem 'devise' gem 'grape' gem 'rack-cors', :require =&gt; 'rack/cors' </code></pre> <p>My current implementation has only APIs with following Routes(<strong><em>routes.rb</em></strong>):</p> <pre><code>api_base /api API::Base GET /:version/posts(.:format) GET /:version/posts/:id(.:format) POST /:version/posts(.:format) DELETE /:version/posts/:id(.:format) POST /:version/users/authenticate(.:format) POST /:version/users/register(.:format) DELETE /:version/users/logout(.:format) </code></pre> <p>I created have following model <strong><em>user.rb</em></strong></p> <pre><code>class User include Mongoid::Document devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable field :email, type: String, default: "" field :encrypted_password, type: String, default: "" field :authentication_token, type: String before_save :ensure_authentication_token! def ensure_authentication_token! self.authentication_token ||= generate_authentication_token end private def generate_authentication_token loop do token = Devise.friendly_token break token unless User.where(authentication_token: token).first end end end </code></pre> <p>In my controllers I created following folder structure: <em>controllers->api->v1</em> and I have created following shared module Authentication (<strong><em>authentication.rb</em></strong>)</p> <pre><code>module API module V1 module Authentication extend ActiveSupport::Concern included do before do error!("401 Unauthorized", 401) unless authenticated? end helpers do def warden env['warden'] end def authenticated? return true if warden.authenticated? params[:access_token] &amp;&amp; @user = User.find_by(authentication_token: params[:access_token]) end def current_user warden.user || @user end end end end end end </code></pre> <p>So every time when I want to ensure, that my resource will be called with Authentication Token, I can simply add this by calling: <code>include API::V1::Authentication</code> to the Grape resource:</p> <pre><code>module API module V1 class Posts &lt; Grape::API include API::V1::Defaults include API::V1::Authentication </code></pre> <p>Now I have another Grape resource called Users(users.rb) and here I implement methods for authentication, registration and logout.(I think that I mix here apples with pears, and I should extract the login/logout process to another Grape resource - Session).</p> <pre><code>module API module V1 class Users &lt; Grape::API include API::V1::Defaults resources :users do desc "Authenticate user and return user object, access token" params do requires :email, :type =&gt; String, :desc =&gt; "User email" requires :password, :type =&gt; String, :desc =&gt; "User password" end post 'authenticate' do email = params[:email] password = params[:password] if email.nil? or password.nil? error!({:error_code =&gt; 404, :error_message =&gt; "Invalid email or password."}, 401) return end user = User.find_by(email: email.downcase) if user.nil? error!({:error_code =&gt; 404, :error_message =&gt; "Invalid email or password."}, 401) return end if !user.valid_password?(password) error!({:error_code =&gt; 404, :error_message =&gt; "Invalid email or password."}, 401) return else user.ensure_authentication_token! user.save status(201){status: 'ok', token: user.authentication_token } end end desc "Register user and return user object, access token" params do requires :first_name, :type =&gt; String, :desc =&gt; "First Name" requires :last_name, :type =&gt; String, :desc =&gt; "Last Name" requires :email, :type =&gt; String, :desc =&gt; "Email" requires :password, :type =&gt; String, :desc =&gt; "Password" end post 'register' do user = User.new( first_name: params[:first_name], last_name: params[:last_name], password: params[:password], email: params[:email] ) if user.valid? user.save return user else error!({:error_code =&gt; 404, :error_message =&gt; "Invalid email or password."}, 401) end end desc "Logout user and return user object, access token" params do requires :token, :type =&gt; String, :desc =&gt; "Authenticaiton Token" end delete 'logout' do user = User.find_by(authentication_token: params[:token]) if !user.nil? user.remove_authentication_token! status(200) { status: 'ok', token: user.authentication_token } else error!({:error_code =&gt; 404, :error_message =&gt; "Invalid token."}, 401) end end end end end end </code></pre> <p>I realize that I present here a ton of code and it might not make sense, but this is what I currently have and I'm able to use the <code>authentication_token</code> for calls against my API which are protected by module <code>Authentication</code>.</p> <p>I feel like this solution is not good, but I really looking for easier way how to achieve user authentication through APIs. I have several questions which I listed below.</p> <p><strong>Questions</strong></p> <ol> <li>Do you think this kind of implementation is dangerous, if so, why? - I think that it is, because of the usage of one token. Is there a way how to improve this pattern? I've also seen implementation with separate model <code>Token</code> which has expiration time, etc. But I think this is almost like reinventing wheel, because for this purpose I can implement OAuth2. I would like to have lighter solution.</li> <li>It is good practice to create new module for Authentication and include it only into resources where it is needed?</li> <li>Do you know about any good tutorial on this topic - implementing Rails + Devise + Grape? Additionally, do you know about any good open-source Rails project, which is implemented this way?</li> <li>How can I implement it with different approach which is more safer?</li> </ol> <p>I apologize for such a long post, but I hope that more people has the same problem and it might help me to find more answers on my questions.</p>
26,701,831
3
1
null
2014-10-29 06:28:49.65 UTC
16
2022-01-12 14:30:51.66 UTC
null
null
null
null
1,290,852
null
1
23
ruby-on-rails|api|ruby-on-rails-4|devise|ruby-grape
15,006
<p>Add token_authenticable to devise modules (works with devise versions &lt;=3.2)</p> <p>In user.rb add :token_authenticatable to the list of devise modules, it should look something like below:</p> <pre><code>class User &lt; ActiveRecord::Base # ..code.. devise :database_authenticatable, :token_authenticatable, :invitable, :registerable, :recoverable, :rememberable, :trackable, :validatable attr_accessible :name, :email, :authentication_token before_save :ensure_authentication_token # ..code.. end </code></pre> <p>Generate Authentication token on your own (If devise version > 3.2)</p> <pre><code>class User &lt; ActiveRecord::Base # ..code.. devise :database_authenticatable, :invitable, :registerable, :recoverable, :rememberable, :trackable, :validatable attr_accessible :name, :email, :authentication_token before_save :ensure_authentication_token def ensure_authentication_token self.authentication_token ||= generate_authentication_token end private def generate_authentication_token loop do token = Devise.friendly_token break token unless User.where(authentication_token: token).first end end </code></pre> <p>Add migration for authentiction token</p> <pre><code>rails g migration add_auth_token_to_users invoke active_record create db/migrate/20141101204628_add_auth_token_to_users.rb </code></pre> <p>Edit migration file to add :authentication_token column to users</p> <pre><code>class AddAuthTokenToUsers &lt; ActiveRecord::Migration def self.up change_table :users do |t| t.string :authentication_token end add_index :users, :authentication_token, :unique =&gt; true end def self.down remove_column :users, :authentication_token end end </code></pre> <p>Run migrations</p> <p><code>rake db:migrate</code></p> <p>Generate token for existing users</p> <p>We need to call save on every instance of user that will ensure authentication token is present for each user.</p> <p><code>User.all.each(&amp;:save)</code></p> <p>Secure Grape API using auth token</p> <p>You need to add below code to the API::Root in-order to add token based authentication. If you are unware of API::Root then please read <a href="http://funonrails.com/2014/03/building-restful-api-using-grape-in-rails/" rel="noreferrer">Building RESTful API using Grape</a></p> <p>In below example, We are authenticating user based on two scenarios – If user is logged on to the web app then use the same session – If session is not available and auth token is passed then find user based on the token</p> <pre><code># lib/api/root.rb module API class Root &lt; Grape::API prefix 'api' format :json rescue_from :all, :backtrace =&gt; true error_formatter :json, API::ErrorFormatter before do error!("401 Unauthorized", 401) unless authenticated end helpers do def warden env['warden'] end def authenticated return true if warden.authenticated? params[:access_token] &amp;&amp; @user = User.find_by_authentication_token(params[:access_token]) end def current_user warden.user || @user end end mount API::V1::Root mount API::V2::Root end end </code></pre>
20,348,007
How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?
<p>I'm typing a shell script to find out the total physical memory in some RHEL linux boxes.</p> <p>First of all I want to stress that I'm interested in the <strong>total physical memory</strong> recognized by kernel, not just the <strong>available memory</strong>. Therefore, please, avoid answers suggesting to read <strong>/proc/meminfo</strong> or to use the <strong>free</strong>, <strong>top</strong> or <strong>sar</strong> commands -- In all these cases, their "<strong>total memory</strong>" values mean "<strong>available memory</strong>" ones.</p> <p>The first thought was to read the boot kernel messages:</p> <pre><code>Memory: 61861540k/63438844k available (2577k kernel code, 1042516k reserved, 1305k data, 212k init) </code></pre> <p>But in some linux boxes, due to the use of EMC2's PowerPath software and its <strong>flooding</strong> boot messages in the kernel startup, that useful boot kernel message is not available, not even in the <strong>/var/log/dmesg</strong> file.</p> <p>The second option was the <strong>dmidecode</strong> command (I'm warned against the possible mismatch of kernel recognized RAM and real RAM due to the limitations of some older kernels and architectures). The option <strong>--memory</strong> simplifies the script but I realized that older releases of that command has no <strong>--memory</strong> option.</p> <p>My last chance was the <strong>getconf</strong> command. It reports the memory page size, but not the total number of physical pages -- the <strong>_PHYS_PAGES</strong> system variable seems to be the available physical pages, not the total physical pages.</p> <pre> # getconf -a | grep PAGES PAGESIZE 4096 _AVPHYS_PAGES 1049978 _PHYS_PAGES 15466409 </pre> <p>My question: Is there another way to get the total amount of physical memory, suitable to be parsed by a shell script?</p>
20,399,659
13
1
null
2013-12-03 10:02:53.573 UTC
34
2020-09-18 19:31:20.69 UTC
2015-10-27 16:25:08.11 UTC
null
1,880,339
null
2,545,194
null
1
132
linux|ram|memory-size
269,735
<p>If you're interested in the physical RAM, use the command <code>dmidecode</code>. It gives you a <em>lot</em> more information than just that, but depending on your use case, you might also want to know if the 8G in the system come from 2x4GB sticks or 4x2GB sticks.</p>
7,314,901
How to add/remove PKCS7 padding from an AES encrypted string?
<p>I'm trying to encrypt/decrypt a string using 128 bit AES encryption (ECB). What I want to know is how I can add/remove the PKCS7 padding to it. It seems that the Mcrypt extension can take care of the encryption/decryption, but the padding has to be added/removed manually.</p> <p>Any ideas?</p>
7,324,793
3
4
null
2011-09-06 04:23:54.697 UTC
15
2020-09-09 13:42:43.96 UTC
2011-09-07 02:27:42.19 UTC
null
49,153
null
49,153
null
1
21
php|encryption|aes|mcrypt|pkcs#7
44,277
<p>Let's see. PKCS #7 is described in RFC 5652 (Cryptographic Message Syntax).</p> <p>The padding scheme itself is given in section <a href="https://www.rfc-editor.org/rfc/rfc5652#section-6.3" rel="nofollow noreferrer">6.3. Content-encryption Process</a>. It essentially says: append that many bytes as needed to fill the given block size (but at least one), and each of them should have the padding length as value.</p> <p>Thus, looking at the last decrypted byte we know how many bytes to strip off. (One could also check that they all have the same value.)</p> <p>I could now give you a pair of PHP functions to do this, but my PHP is a bit rusty. So either do this yourself (then feel free to edit my answer to add it in), or have a look at the <a href="http://php.net/manual/en/function.mcrypt-encrypt.php#usernotes" rel="nofollow noreferrer">user-contributed notes</a> to the mcrypt documentation - quite some of them are about padding and provide an implementation of PKCS #7 padding.</p> <hr /> <p>So, let's look on the <a href="http://www.php.net/manual/en/function.mcrypt-encrypt.php#105173" rel="nofollow noreferrer">first note there</a> in detail:</p> <pre><code>&lt;?php function encrypt($str, $key) { $block = mcrypt_get_block_size('des', 'ecb'); </code></pre> <p>This gets the block size of the used algorithm. In your case, you would use <code>aes</code> or <code>rijndael_128</code> instead of <code>des</code>, I suppose (I didn't test it). (Instead, you could simply take <code>16</code> here for AES, instead of invoking the function.)</p> <pre><code> $pad = $block - (strlen($str) % $block); </code></pre> <p>This calculates the padding size. <a href="http://de3.php.net/manual/en/function.strlen.php" rel="nofollow noreferrer"><code>strlen($str)</code></a> is the length of your data (in bytes), <code>% $block</code> gives the remainder modulo <code>$block</code>, i.e. the number of data bytes in the last block. <code>$block - ...</code> thus gives the number of bytes needed to fill this last block (this is now a number between <code>1</code> and <code>$block</code>, inclusive).</p> <pre><code> $str .= str_repeat(chr($pad), $pad); </code></pre> <p><a href="http://de3.php.net/manual/en/function.str-repeat.php" rel="nofollow noreferrer"><code>str_repeat</code></a> produces a string consisting of a repetition of the same string, here a repetition of the <a href="http://de3.php.net/manual/en/function.chr.php" rel="nofollow noreferrer">character given by</a> <code>$pad</code>, <code>$pad</code> times, i.e. a string of length <code>$pad</code>, filled with <code>$pad</code>. <code>$str .= ...</code> appends this padding string to the original data.</p> <pre><code> return mcrypt_encrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB); </code></pre> <p>Here is the encryption itself. Use <a href="http://de3.php.net/manual/en/mcrypt.ciphers.php" rel="nofollow noreferrer"><code>MCRYPT_RIJNDAEL_128</code></a> instead of <code>MCRYPT_DES</code>.</p> <pre><code> } </code></pre> <p>Now the other direction:</p> <pre><code> function decrypt($str, $key) { $str = mcrypt_decrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB); </code></pre> <p>The decryption. (You would of course change the algorithm, as above). $str is now the decrypted string, including the padding.</p> <pre><code> $block = mcrypt_get_block_size('des', 'ecb'); </code></pre> <p>This is again the block size. (See above.)</p> <pre><code> $pad = ord($str[($len = strlen($str)) - 1]); </code></pre> <p>This looks a bit strange. Better write it in multiple steps:</p> <pre><code> $len = strlen($str); $pad = ord($str[$len-1]); </code></pre> <p><code>$len</code> is now the length of the padded string, and <code>$str[$len - 1]</code> is the last character of this string. <a href="http://de3.php.net/manual/en/function.ord.php" rel="nofollow noreferrer"><code>ord</code></a> converts this to a number. Thus <code>$pad</code> is the number which we previously used as the fill value for the padding, and this is the padding length.</p> <pre><code> return substr($str, 0, strlen($str) - $pad); </code></pre> <p>So now we cut off the last <code>$pad</code> bytes from the string. (Instead of <code>strlen($str)</code> we could also write <code>$len</code> here: <code>substr($str, 0, $len - $pad)</code>.).</p> <pre><code> } ?&gt; </code></pre> <p>Note that instead of using <code>substr($str, $len - $pad)</code>, one can also write <code>substr($str, -$pad)</code>, as the <code>substr</code> function in PHP has a special-handling for negative operands/arguments, to count from the end of the string. (I don't know if this is more or less efficient than getting the length first and and calculating the index manually.)</p> <p>As said before and noted in the comment by rossum, instead of simply stripping off the padding like done here, you should check that it is correct - i.e. look at <code>substr($str, $len - $pad)</code>, and check that all its bytes are <code>chr($pad)</code>. This serves as a slight check against corruption (although this check is more effective if you use a chaining mode instead of ECB, and is not a replacement for a real MAC).</p> <hr /> <p>(And still, tell your client they should think about changing to a more secure mode than ECB.)</p>
7,099,127
Get the actual Javascript Error object with window.onerror
<p>Javascript has this great callback <code>window.onerror</code>. It's quite convenient to track any error. However, it calls with the error name, the file name and the line. It's certainly not as rich as getting the actual error object from a <code>try...catch</code> statement. The actual error object contains a lot more data, so I am trying to get that. Unfortunately, <code>try...catch</code> statement do not work fine when you start having async code.</p> <p>Is there a way to combine and get the best of both worlds? I initially looked for a way to get the <em>last</em> error triggered within an <code>onerror</code> block, but it looks like JS doesn't store that.</p> <p>Any clue?</p>
7,099,325
3
1
null
2011-08-17 20:34:35.737 UTC
11
2016-02-02 14:32:22.4 UTC
null
null
null
null
73,987
null
1
50
javascript|error-handling|onerror
22,767
<p>If you're referring to stack trace of the error object, then AFAIK, this is not possible. </p> <p>Simple reason being that a stack trace is related to an execution context in which runtime exceptions (handled with try...catch...finally) were created or thrown (with <code>new Error()</code> or <code>throw</code>).</p> <p>Whereas when <code>window.onerror</code> is invoked, it is called within a different context. </p> <p>You can get some mileage by inspecting <code>window.event</code> (not available on FF) in your <code>onerror</code> handler.</p>
7,801,646
XML string to DataTable in C#
<p>How to convert XML string to DataTable in C#?</p> <p>I tried the following code:</p> <pre><code>public DataTable stam() { string xmlData = "&lt;Names&gt;&lt;Name&gt;a&lt;/Name&gt;&lt;Name&gt;b&lt;/Name&gt;&lt;Name&gt;c&lt;/Name&gt;&lt;Name&gt;d&lt;/Name&gt;&lt;/Names&gt;"; XElement x = XElement.Parse(xmlData); DataTable dt = new DataTable(); XElement setup = (from p in x.Descendants() select p).First(); foreach (XElement xe in setup.Descendants()) // build your DataTable dt.Columns.Add(new DataColumn(xe.Name.ToString(), typeof(string))); // add columns to your dt var all = from p in x.Descendants(setup.Name.ToString()) select p; foreach (XElement xe in all) { DataRow dr = dt.NewRow(); foreach (XElement xe2 in xe.Descendants()) dr[xe2.Name.ToString()] = xe2.Value; //add in the values dt.Rows.Add(dr); } return dt; } </code></pre> <p>and it returns an empty DataTable.</p>
7,801,673
1
0
null
2011-10-18 01:57:20.95 UTC
10
2019-08-28 13:17:18.247 UTC
2019-08-28 13:17:18.247 UTC
null
3,840,840
null
990,635
null
1
24
c#|.net|xml|datatable
70,542
<pre><code>public DataTable stam() { StringReader theReader = new StringReader(xmlData); DataSet theDataSet = new DataSet(); theDataSet.ReadXml(theReader); return theDataSet.Tables[0]; } </code></pre> <p>You can use a <code>StringReader</code> to load it into a <code>DataSet</code>. From there, the table with the first index will contain the <code>DataTable</code>.</p>
1,986,608
CSS Styling Checkboxes
<p>Okay, so I've seen lots of solutions for styling checkboxes via CSS on the web. However, I'm looking for something slightly more robust, and I'm wondering if someone can help. Basically, I want to have <a href="http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/" rel="noreferrer">this solution</a>, but with the ability to have a CSS-specified color overlaying a gray checkbox. I need this because I will have unpredictable numbers of different checkboxes, each needing a different color, and I don't want to create vast amounts of different images to handle this. Anyone have any ideas on how to achieve this?</p>
1,986,931
4
1
null
2009-12-31 18:46:34.31 UTC
12
2013-06-13 12:36:52.13 UTC
null
null
null
David Savage
null
null
1
20
css|checkbox
86,291
<p>I created a transparent png, where the outside is white, and the checkbox is partially transparent. I modified the code to put a backgroundColor on the element, and voila!, a colorized checkbox.</p> <p><a href="http://i48.tinypic.com/raz13m.jpg" rel="noreferrer">http://i48.tinypic.com/raz13m.jpg</a> (It says jpg, but it's a png).</p> <p>I would post the example, but I don't know of a good way to show it. Any good sandbox sites out there?</p> <p>This, of course, depends on png support. You could poorly do this with gif, or put a semi-transparent css layer over the image, like you suggested, and then use a gif mask to mask out the bleed of the colored box. This method assumes transparency support.</p> <p>My png method uses the css, js from the page you linked to, with these changes:</p> <p>JS:</p> <pre><code> // Changed all instances of '== "styled"' to '.search(...)' // to handle the additional classes needed for the colors (see CSS/HTML below) if((inputs[a].type == "checkbox" || inputs[a].type == "radio") &amp;&amp; inputs[a].className.search(/^styled/) != -1) { span[a] = document.createElement("span"); // Added '+ ...' to this line to handle additional classes on the checkbox span[a].className = inputs[a].type + inputs[a].className.replace(/^styled/, ""); </code></pre> <p>CSS:</p> <pre><code> .checkbox, .radio { width: 19px; height: 25px; padding: 0px; /* Removed padding to eliminate color bleeding around image you could make the image wider on the right to get the padding back */ background: url(checkbox2.png) no-repeat; display: block; clear: left; float: left; } .green { background-color: green; } .red { background-color: red; } etc... </code></pre> <p>HTML:</p> <pre><code>&lt;p&gt;&lt;input type="checkbox" name="1" class="styled green"/&gt; (green)&lt;/p&gt; &lt;p&gt;&lt;input type="checkbox" name="2" class="styled red" /&gt; (red)&lt;/p&gt; &lt;p&gt;&lt;input type="checkbox" name="3" class="styled purple" /&gt; (purple)&lt;/p&gt; </code></pre> <p>Hope that makes sense.</p> <p><strong>Edit:</strong></p> <p>Here is a jQuery example that illustrates the principle with checkboxes:</p> <p><a href="http://jsfiddle.net/jtbowden/xP2Ns/" rel="noreferrer">http://jsfiddle.net/jtbowden/xP2Ns/</a></p>
28,691,344
How to call a Java program from PowerShell?
<p>I need to call a java program (jar file )from PowerShell. The following code works:</p> <pre><code>java -jar $cls --js $dcn --js_output_file $dco </code></pre> <p>But I need to have to run the app in a process (using <code>Start-Process</code>).</p> <p>I am trying the following with no sucess:</p> <pre><code>Start-Process -FilePath java -jar $cls --js $dcn --js_output_file $dco -wait -windowstyle Normal </code></pre> <p>Error:</p> <pre><code>Start-Process : A parameter cannot be found that matches parameter name 'jar'. </code></pre> <p>Any idea how to fix it?</p>
28,691,884
3
2
null
2015-02-24 08:44:22.57 UTC
7
2021-02-24 05:23:16.363 UTC
2015-02-24 09:04:15.457 UTC
null
379,008
null
379,008
null
1
9
java|windows|powershell
51,891
<p>You will need to use following format for powershell:</p> <pre><code> Start-Process java -ArgumentList '-jar', 'MyProgram.jar' ` -RedirectStandardOutput '.\console.out' -RedirectStandardError '.\console.err' </code></pre> <p>Or other option you can use is Start-job:</p> <pre><code>Start-Job -ScriptBlock { &amp; java -jar MyProgram.jar &gt;console.out 2&gt;console.err } </code></pre>
25,996,032
How to Change programmatically Edittext Cursor Color in android?
<p>In android we can change the cursor color via: </p> <p><code>android:textCursorDrawable="@drawable/black_color_cursor"</code>. </p> <p>How can we do this dynamically?</p> <p>In my case I have set cursor drawable to white, but i need to change black How to do ?</p> <pre><code> // Set an EditText view to get user input final EditText input = new EditText(nyactivity); input.setTextColor(getResources().getColor(R.color.black)); </code></pre>
26,543,290
11
1
null
2014-09-23 13:11:17.273 UTC
8
2022-04-28 07:18:11.62 UTC
2017-09-10 05:50:17.877 UTC
null
1,033,581
null
1,600,058
null
1
29
java|android
33,678
<p>Using some reflection did the trick for me</p> <p>Java:</p> <pre><code>// https://github.com/android/platform_frameworks_base/blob/kitkat-release/core/java/android/widget/TextView.java#L562-564 Field f = TextView.class.getDeclaredField("mCursorDrawableRes"); f.setAccessible(true); f.set(yourEditText, R.drawable.cursor); </code></pre> <p>XML:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" &gt; &lt;solid android:color="#ff000000" /&gt; &lt;size android:width="1dp" /&gt; &lt;/shape&gt; </code></pre> <hr> <p>Here is a method that you can use that doesn't need an XML:</p> <pre><code>public static void setCursorColor(EditText view, @ColorInt int color) { try { // Get the cursor resource id Field field = TextView.class.getDeclaredField("mCursorDrawableRes"); field.setAccessible(true); int drawableResId = field.getInt(view); // Get the editor field = TextView.class.getDeclaredField("mEditor"); field.setAccessible(true); Object editor = field.get(view); // Get the drawable and set a color filter Drawable drawable = ContextCompat.getDrawable(view.getContext(), drawableResId); drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN); Drawable[] drawables = {drawable, drawable}; // Set the drawables field = editor.getClass().getDeclaredField("mCursorDrawable"); field.setAccessible(true); field.set(editor, drawables); } catch (Exception ignored) { } } </code></pre>
26,347,071
What is the purpose of FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters) inside Global.asax
<p>I have read the similar question<a href="https://stackoverflow.com/questions/5343946/what-is-the-purpose-of-registerglobalfilters">What is the purpose of RegisterGlobalFilter</a></p> <p>but unable to get the answer, the question somewhat revolves around some other stuff too and the anwser doesn't seems fullfilling to me.</p> <p>My question is:- what is the purpose of this line inside global.asax in MVC 5 <code>FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);</code></p> <ol> <li>Why it is needed ? </li> <li>What is the purpose of adding/registering filters? </li> <li>What does the filter have to do?</li> </ol>
26,347,647
1
1
null
2014-10-13 19:02:30.963 UTC
7
2014-10-13 20:04:40.91 UTC
2017-05-23 12:02:23.73 UTC
null
-1
null
3,040,682
null
1
43
c#|asp.net-mvc
45,803
<p>The <code>FilterConfig</code> is a custom class in your code, normally under the App_Start folder and generally looks somewhat like this:</p> <pre><code>public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } </code></pre> <p>You can add custom filters to this list that should be executed on each request. If you inherit from the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.filterattribute.aspx" rel="noreferrer"><code>FilterAttribute</code></a> class or one of its <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.filterattribute%28v=vs.118%29.aspx#inheritanceContinued" rel="noreferrer">inheritors</a> you can create your own filters, for instance a log filter.</p> <p>You can also apply these filters to controllers that requires certain constraints. For instance, if you add the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.requirehttpsattribute.aspx" rel="noreferrer"><code>[RequireHttps]</code></a> filter attribute (example below) to a controller or a method in your controller, the user must use a https request in order to execute the code in the method. So instead of handling it in each method, the filter takes care of it.</p> <pre><code>[RequireHttps] public class MyController : ApiController { // only https requests will get through to this method. [HttpGet] public IHttpActionResult Get() { return Ok(); } } </code></pre> <p>You can think of it as a little box that sits between the users browser and your controller and <em>filters</em> out any invalid requests, or one the executes when a controller is done and you need to postprocess the result to the user.</p> <p>If you want to read more, msdn has more details regarding filters at <a href="http://msdn.microsoft.com/en-us/library/gg416513%28VS.98%29.aspx" rel="noreferrer">Filtering in ASP.NET MVC</a>.</p>
36,332,487
Move snackbar above the bottom bar
<p>I am facing some problems with new bottom bar.<br> I can't force to move the snackbar above the bottom bar (this is how design guideline told me should be <a href="https://www.google.com/design/spec/components/bottom-navigation.html#bottom-navigation-specs" rel="noreferrer">https://www.google.com/design/spec/components/bottom-navigation.html#bottom-navigation-specs</a>).</p> <p>This is my activity_main.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:openDrawer="start"&gt; &lt;include layout="@layout/app_bar_main_activity" android:layout_width="match_parent" android:layout_height="match_parent" /&gt; &lt;android.support.design.widget.NavigationView android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:fitsSystemWindows="true" app:headerLayout="@layout/nav_header_main_activity" app:menu="@menu/activity_main_drawer" /&gt; &lt;/android.support.v4.widget.DrawerLayout&gt; </code></pre> <p>This is my app_bar_main_activity.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context="test.tab_activity"&gt; &lt;android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="@dimen/appbar_padding_top" android:theme="@style/MyAppTheme.NoActionBar.AppBarOverlay"&gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/main_activity_toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:layout_scrollFlags="scroll|enterAlways" app:popupTheme="@style/MyAppTheme.NoActionBar.PopupOverlay"&gt; &lt;/android.support.v7.widget.Toolbar&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;android.support.v4.view.ViewPager android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"&gt; &lt;android.support.v4.view.ViewPager android:id="@+id/view_pager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /&gt; &lt;android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:layout_margin="@dimen/fab_margin" android:src="@drawable/ic_add_white_24dp" /&gt; &lt;android.support.design.widget.TabLayout android:id="@+id/tab_layout" style="@style/AppTabLayout" android:layout_width="match_parent" android:layout_height="56dp" android:background="?attr/colorPrimary" /&gt; &lt;/LinearLayout&gt; </code></pre> <p></p> <p>The snackbar in main_activity.java looks like this</p> <pre><code>FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(findViewById(R.id.main_content), "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); </code></pre> <p><a href="https://i.stack.imgur.com/eG9BR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eG9BR.png" alt="Wrong...snackbar should be above bottom bar"></a></p>
36,333,022
13
6
null
2016-03-31 11:44:15.263 UTC
19
2022-03-30 12:27:37.393 UTC
2019-11-01 20:53:04.303 UTC
null
2,016,562
null
5,789,299
null
1
70
android|layout|android-snackbar|snackbar
59,766
<p>replace your xml -></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context="test.tab_activity"&gt; &lt;android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/main_activity_toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:layout_scrollFlags="scroll|enterAlways"&gt; &lt;/android.support.v7.widget.Toolbar&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;android.support.v4.view.ViewPager android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"&gt; &lt;android.support.design.widget.CoordinatorLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:id="@+id/placeSnackBar"&gt; &lt;android.support.v4.view.ViewPager android:id="@+id/view_pager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /&gt; &lt;android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:layout_margin="@dimen/fab_margin" android:src="@drawable/ic_menu_gallery" /&gt; &lt;/android.support.design.widget.CoordinatorLayout&gt; &lt;android.support.design.widget.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="56dp" android:background="?attr/colorPrimary" /&gt; &lt;/LinearLayout&gt; &lt;/android.support.design.widget.CoordinatorLayout&gt; </code></pre> <p>and The Snackbar code will be </p> <pre><code>Snackbar.make(findViewById(R.id.placeSnackBar), "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); </code></pre>
7,167,212
How do I connect to a Websphere Datasource with a given JNDI name?
<p>I'm using Websphere Portal 7.0 and creating a portlet with RAD 8.0. My portlet is trying to make a db2 connection to a remote server. I wrote a java program locally to do a basic JDBC connection to the server and get records from a table. The code works fine; however, when I add the code to my portlet as well as the db2jcc4.jar, the connection doesn't work. I'm using the basic: </p> <pre><code>Connection connection = DriverManager.getConnection("jdbc:db2://server:port/db:user=user;password=pw;"); </code></pre> <p>I figure that using the Websphere datasource is the right way to go. I know the JNDI name for the datasource, but I'm not finding clear cut examples on how to make a connection. Several examples use a DataSource class (I typed this in and this doesn't seem like it comes from a native java package so what import do I use here?) coupled with a Context. I've come across code like: </p> <pre><code>Context ctx = new InitialContext(); ctx.lookup("jdbc/xxxx"); </code></pre> <p>... Can someone break this down for me? </p> <p><strong>EDIT 1</strong></p> <p>I've updated my code per the answers listed. I really think I'm getting closer. Here is my getConnection() method:</p> <pre><code>private Connection getConnection() throws SQLException { javax.naming.InitialContext ctx = null; javax.sql.DataSource ds = null; System.out.println("Attempting connection..." + DateUtil.now() ); try { ctx = new javax.naming.InitialContext(); ds = (javax.sql.DataSource) ctx.lookup("java:comp/env/jdbc/db"); connection = ds.getConnection(); } catch (NamingException e) { System.out.println("peformanceappraisalstatus: COULDN'T CREATE CONNECTION!"); e.printStackTrace(); } System.out.println("connection: " + connection.getClass().getName() + " at " + DateUtil.now()); return connection; } </code></pre> <p>My entire web.xml file looks like: </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app id="WebApp_ID" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"&gt; &lt;display-name&gt;PeformanceAppraisalStatus&lt;/display-name&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.html&lt;/welcome-file&gt; &lt;welcome-file&gt;index.htm&lt;/welcome-file&gt; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt; &lt;welcome-file&gt;default.html&lt;/welcome-file&gt; &lt;welcome-file&gt;default.htm&lt;/welcome-file&gt; &lt;welcome-file&gt;default.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;resource-ref&gt; &lt;description&gt; Datasource connection to Db&lt;/description&gt; &lt;res-ref-name&gt;jdbc/db&lt;/res-ref-name&gt; &lt;res-type&gt;javax.sql.DataSource&lt;/res-type&gt; &lt;res-auth&gt;Container&lt;/res-auth&gt; &lt;res-sharing-scope&gt;Shareable&lt;/res-sharing-scope&gt; &lt;/resource-ref&gt; &lt;/web-app&gt; </code></pre> <p>I am seeing an error that describes the very thing you guys are telling me Websphere should prompt me to do, but doesn't:</p> <pre><code>SRVE0169I: Loading Web Module: PeformanceAppraisalStatus. [8/23/11 18:08:02:166 CDT] 00000009 InjectionProc E CWNEN0044E: A resource reference binding could not be found for the jdbc/db resource reference, defined for the PeformanceAppraisalStatus component. [8/23/11 18:08:02:169 CDT] 00000009 InjectionEngi E CWNEN0011E: The injection engine failed to process bindings for the metadata. </code></pre> <p>Yes, I know that I've mispelled performance as peformance throughout the app. </p> <p><strong>SOLUTION</strong></p> <p>I was so very close. Here are the missing bits that made it all fall into place:</p> <pre><code>web.xml: &lt;resource-ref&gt; &lt;description&gt; Datasource connection to db&lt;/description&gt; &lt;res-ref-name&gt;jdbc/db&lt;/res-ref-name&gt; &lt;res-type&gt;javax.sql.DataSource&lt;/res-type&gt; &lt;res-auth&gt;Container&lt;/res-auth&gt; &lt;res-sharing-scope&gt;Shareable&lt;/res-sharing-scope&gt; &lt;mapped-name&gt;jdbc/db&lt;/mapped-name&gt; &lt;/resource-ref&gt; ibm-web-bnd.xml: &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-bnd xmlns="http://websphere.ibm.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee http://websphere.ibm.com/xml/ns/javaee/ibm-web-bnd_1_0.xsd" version="1.0"&gt; &lt;virtual-host name="default_host" /&gt; &lt;resource-ref name="jdbc/db" binding-name="jdbc/mydatasource" /&gt; &lt;/web-bnd&gt; </code></pre> <p>It appears that the ibm-web-bnd.xml file handles the binding between the project resource name and the datasource in websphere. Once I added the line:</p> <pre><code>&lt;resource-ref name="jdbc/db" binding-name="jdbc/mydatasource" /&gt; </code></pre> <p>Websphere Portal seemed appeased. My code is working and connecting to the database now. </p>
7,167,467
6
1
null
2011-08-23 20:34:26.683 UTC
13
2018-07-09 18:30:45.98 UTC
2018-07-09 18:30:45.98 UTC
null
2,370,483
null
1,709,186
null
1
21
java|db2|websphere|jndi|ibm-rational
117,828
<p>You need to define a <strong>resource reference</strong> in your application and then map that logical resource reference to the physical resource (data source) during deployment.</p> <p>In your <code>web.xml</code>, add the following configuration (modifying the names and properties as appropriate):</p> <pre><code>&lt;resource-ref&gt; &lt;description&gt;Resource reference to my database&lt;/description&gt; &lt;res-ref-name&gt;jdbc/MyDB&lt;/res-ref-name&gt; &lt;res-type&gt;javax.sql.DataSource&lt;/res-type&gt; &lt;res-auth&gt;Container&lt;/res-auth&gt; &lt;res-sharing-scope&gt;Shareable&lt;/res-sharing-scope&gt; &lt;/resource-ref&gt; </code></pre> <p>Then, during application deployment, WAS will prompt you to map this resource reference (<code>jdbc/MyDB</code>) to the data source you created in WAS.</p> <p>In your code, you can obtain the DataSource similar to how you've shown it in your example; however, the JNDI name you'll use to look it up should actually be the resource reference's name you defined (<code>res-ref-name</code>), rather than the JNDI name of the physical data source. Also, you'll need to prefix the res-ref-name with the application naming context (<code>java:comp/env/</code>).</p> <pre><code>Context ctx = new InitialContext(); DataSource dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/MyDB"); </code></pre>
7,281,699
Aligning to cache line and knowing the cache line size
<p>To prevent false sharing, I want to align each element of an array to a cache line. So first I need to know the size of a cache line, so I assign each element that amount of bytes. Secondly I want the start of the array to be aligned to a cache line. </p> <p>I am using Linux and 8-core x86 platform. First how do I find the cache line size. Secondly, how do I align to a cache line in C. I am using the gcc compiler. </p> <p>So the structure would be following for example, assuming a cache line size of 64.</p> <pre><code>element[0] occupies bytes 0-63 element[1] occupies bytes 64-127 element[2] occupies bytes 128-191 </code></pre> <p>and so on, assuming of-course that 0-63 is aligned to a cache line.</p>
7,281,770
7
4
null
2011-09-02 09:43:30.213 UTC
42
2020-12-27 14:23:25.797 UTC
2015-07-20 13:53:22.633 UTC
null
183,120
null
760,807
null
1
69
c|linux|caching|computer-architecture|memory-alignment
75,277
<p>To know the sizes, you need to look it up using the documentation for the processor, afaik there is no programatic way to do it. On the plus side however, most cache lines are of a standard size, based on intels standards. On x86 cache lines are 64 bytes, however, to prevent false sharing, you need to follow the guidelines of the processor you are targeting (intel has some special notes on its netburst based processors), generally you need to align to 64 bytes for this (intel states that you should also avoid crossing 16 byte boundries). </p> <p>To do this in C or C++ requires that you use the standard <code>aligned_alloc</code> function or one of the compiler specific specifiers such as <code>__attribute__((align(64)))</code> or <code>__declspec(align(64))</code>. To pad between members in a struct to split them onto different cache lines, you need on insert a member big enough to align it to the next 64 byte boundery</p>
7,164,630
How to change shape color dynamically?
<p>I have </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"&gt; &lt;solid android:color="#FFFF00" /&gt; &lt;padding android:left="7dp" android:top="7dp" android:right="7dp" android:bottom="7dp" /&gt; &lt;/shape&gt; &lt;TextView android:background="@drawable/test" android:layout_height="45dp" android:layout_width="100dp" android:text="Moderate" /&gt; </code></pre> <p>So now I want this shape to change colors based on information I get back from a web service call. So it could be maybe yellow or green or red or whatever depending on the color I receive from the web serivce call.</p> <p>How can I change the color of the shape? Based on this information?</p>
7,165,050
14
2
null
2011-08-23 16:54:21.477 UTC
26
2020-03-17 18:23:41.913 UTC
2011-08-23 17:27:28.427 UTC
null
857,361
null
130,015
null
1
137
android|android-layout|xamarin.android|shapes
134,326
<p>You could modify it simply like this</p> <pre><code>GradientDrawable bgShape = (GradientDrawable)btn.getBackground(); bgShape.setColor(Color.BLACK); </code></pre>
14,219,947
Why do shaders have to be in html file for webgl program?
<p>I have seen the following question where someone asked how to remove shaders from html: <a href="https://stackoverflow.com/questions/5878703/webgl-is-there-an-alternative-to-embedding-shaders-in-html">WebGL - is there an alternative to embedding shaders in HTML?</a></p> <p>There are elaborate workarounds to load in a file containing the shader suggested in the answers to the question.</p> <p>In the tutorial I saw, the shader code is embedded directly in the html. The javascript code refers to it using getElementById. But it's ugly embedding the shader directly in the html for many reasons. Why can't I just refer to it externally using the src= attribute?</p> <pre><code>&lt;script type="x-shader/x-fragment" id="shader-fs" src="util/fs"&gt;&lt;/script&gt; </code></pre> <p>The above doesn't work, I just want to know why not. This is clearly something to do with limitations on script itself, but I don't get it.</p>
14,253,795
3
2
null
2013-01-08 16:47:33.203 UTC
13
2022-05-09 20:27:41.617 UTC
2017-05-23 12:25:52.237 UTC
null
-1
null
233,928
null
1
28
javascript|three.js|glsl|webgl
18,814
<p>You don't have to use <code>&lt;script&gt;</code> tags at all to load a shader program. Most tutorials and examples just use them as a container to store a string in the DOM of the webpage. The script type <code>"x-shader/x-fragment"</code> is meaningless for web browsers, so they don't execute the script. They do, however, store the content of that tag as a string in the DOM which can then later be accessed by "real" scripts. This only works when the script content is in the HTML file. <strong>When you load the script via a src attribute, the content does not become a text childnode of the script tag and thus can not be accessed through the DOM tree</strong>.</p> <p>You can just as well store the sourcecode for the shader as a string in a Javascript file:</p> <pre><code>// myVertextShader.glsl.js var myVertexShaderSrc = "attribute vec3 pos;"+ "void main() {"+ " gl_Position = vec4(pos, 1.0);"+ "}" ; </code></pre> <p>You would then compile the shader like this:</p> <pre><code>var vertexShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertexShader, myVertexShaderSrc); gl.compileShader(vertexShader); gl.attachShader(program, vertexShader); </code></pre>
14,075,029
Have a set of Tasks with only X running at a time
<p>Let's say I have 100 tasks that do something that takes 10 seconds. Now I want to only run 10 at a time like when 1 of those 10 finishes another task gets executed till all are finished.</p> <p>Now I always used <code>ThreadPool.QueueUserWorkItem()</code> for such task but I've read that it is bad practice to do so and that I should use Tasks instead.</p> <p>My problem is that I nowhere found a good example for my scenario so could you get me started on how to achieve this goal with Tasks?</p>
14,075,286
5
4
null
2012-12-28 19:58:03.21 UTC
13
2019-02-19 15:13:39.983 UTC
null
null
null
null
1,590,345
null
1
34
c#|multithreading|task
20,429
<pre><code>SemaphoreSlim maxThread = new SemaphoreSlim(10); for (int i = 0; i &lt; 115; i++) { maxThread.Wait(); Task.Factory.StartNew(() =&gt; { //Your Works } , TaskCreationOptions.LongRunning) .ContinueWith( (task) =&gt; maxThread.Release() ); } </code></pre>
43,233,070
How to convert Range in NSRange?
<p>I am updating my code in swift 3. Getting error in converting Range into NSRange. How to do that in swift 3 ? </p> <pre><code>func nsRange(_ range : Range&lt;String.Index&gt;) -&gt; NSRange { let utf16from = String.UTF16View.Index(range.lowerBound, within: utf16) let utf16to = String.UTF16View.Index(range.upperBound, within: utf16) return NSRange(location: utf16.startIndex.distanceTo(utf16from), length: utf16from.distanceTo(utf16to)) } </code></pre>
43,233,619
1
2
null
2017-04-05 13:45:59.903 UTC
9
2020-01-25 16:15:36.34 UTC
2017-10-05 14:38:22.333 UTC
null
2,303,865
null
6,518,413
null
1
29
swift
25,814
<p><strong>Xcode 11 • Swift 5.1</strong></p> <pre><code>import Foundation extension RangeExpression where Bound == String.Index { func nsRange&lt;S: StringProtocol&gt;(in string: S) -&gt; NSRange { .init(self, in: string) } } </code></pre> <hr> <pre><code>let string = "Hello USA !!! Hello World !!!" if let nsRange = string.range(of: "Hello World")?.nsRange(in: string) { (string as NSString).substring(with: nsRange) // "Hello World" } </code></pre> <p>You can also create the corresponding <code>nsRange(of:)</code> method extending <code>StringProtocol</code>:</p> <pre><code>extension StringProtocol { func nsRange&lt;S: StringProtocol&gt;(of string: S, options: String.CompareOptions = [], range: Range&lt;Index&gt;? = nil, locale: Locale? = nil) -&gt; NSRange? { self.range(of: string, options: options, range: range ?? startIndex..&lt;endIndex, locale: locale ?? .current)? .nsRange(in: self) } func nsRanges&lt;S: StringProtocol&gt;(of string: S, options: String.CompareOptions = [], range: Range&lt;Index&gt;? = nil, locale: Locale? = nil) -&gt; [NSRange] { var start = range?.lowerBound ?? startIndex let end = range?.upperBound ?? endIndex var ranges: [NSRange] = [] while start &lt; end, let range = self.range(of: string, options: options, range: start..&lt;end, locale: locale ?? .current) { ranges.append(range.nsRange(in: self)) start = range.lowerBound &lt; range.upperBound ? range.upperBound : index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex } return ranges } } </code></pre> <hr> <pre><code>let string = "Hello USA !!! Hello World !!!" if let nsRange = string.nsRange(of: "Hello World") { (string as NSString).substring(with: nsRange) // "Hello World" } let nsRanges = string.nsRanges(of: "Hello") print(nsRanges) // "[{0, 5}, {19, 5}]\n" </code></pre>
9,375,018
jQuery alert after 100 pixels scrolled
<p>Is it possible to fire an alert after a user scrolls 100 pixels. </p> <p>Here's what I have so far but I know I'm missing something;</p> <pre><code>$(window).scroll(function() { if (document.documentElement.clientHeight + $(document).scrollTop() == "100px") { alert("You've scrolled 100 pixels."); } }); </code></pre>
9,375,065
3
1
null
2012-02-21 09:26:18.743 UTC
5
2015-06-04 21:14:12.51 UTC
null
null
null
null
851,593
null
1
17
javascript|jquery
54,882
<p>Look at the window .scrollTop (returns an integer):</p> <pre><code>$(window).scroll(function() { if ($(this).scrollTop() === 100) { // this refers to window alert("You've scrolled 100 pixels."); } }); </code></pre> <p>but if you have scrolled 102px it wont trigger the alert box.</p> <p>if you just want to trigger the alert once have a global variable that sets to true if it has been trigged:</p> <pre><code>$(function(){ var hasBeenTrigged = false; $(window).scroll(function() { if ($(this).scrollTop() &gt;= 100 &amp;&amp; !hasBeenTrigged) { // if scroll is greater/equal then 100 and hasBeenTrigged is set to false. alert("You've scrolled 100 pixels."); hasBeenTrigged = true; } }); }); </code></pre> <p>or just unbind the scroll event once the alert box has been trigged:</p> <pre><code>$(function(){ $(window).bind("scroll.alert", function() { var $this = $(this); if ($this.scrollTop() &gt;= 100) { alert("You've scrolled 100 pixels."); $this.unbind("scroll.alert"); } }); }); </code></pre>
9,498,201
Delete file from Pull Request on GitHub
<p>I have make pull request on git (with "xcodeproj/project.pbxproj" file - my fault), so can I delete this file from created Pull Request? Thanks..</p>
9,498,304
7
1
null
2012-02-29 11:24:07.72 UTC
5
2020-07-14 08:24:09.037 UTC
2012-02-29 11:27:06.557 UTC
null
434,799
null
1,095,923
null
1
39
git|github|pull-request
103,278
<ul> <li>Make a commit that deletes this file and push it.</li> <li>Go to your fork's Github page and click <em>Pull Request</em> again. You will get a message stating that you already have a pull request, and that you can adjust the commit range for it.</li> <li>Include your new commit (with the deletion).</li> </ul> <p>The offending file will still be in the changesets to be merged, mind you, so if it contains sensitive data it's best to close the pull request and wipe out the file from your fork's repository first. Github help <a href="http://help.github.com/remove-sensitive-data/" rel="noreferrer">describes</a> how to do that.</p>
19,699,059
Representing Directory & File Structure in Markdown Syntax
<p>I want to describe directory &amp; file structures in Markdown syntax. Is there a way to do it neatly?</p> <pre><code>. ├── _config.yml ├── _drafts │ ├── begin-with-the-crazy-ideas.textile │ └── on-simplicity-in-technology.markdown ├── _includes │ ├── footer.html │ └── header.html ├── _layouts │ ├── default.html │ └── post.html ├── _posts │ ├── 2007-10-29-why-every-programmer-should-play-nethack.textile │ └── 2009-04-26-barcamp-boston-4-roundup.textile ├── _data │ └── members.yml ├── _site └── index.html </code></pre> <p>Edit: Unicode has box drawing characters for this very purpose which can be copy pasted as is: <a href="https://en.wikipedia.org/wiki/Box-drawing_character" rel="noreferrer">https://en.wikipedia.org/wiki/Box-drawing_character</a></p>
19,702,570
12
3
null
2013-10-31 05:27:40.84 UTC
101
2022-05-19 18:53:15.913 UTC
2022-05-19 18:53:15.913 UTC
null
7,134,134
null
718,341
null
1
379
unicode|markdown|directory-structure|project-structure
352,280
<p>If you are concerned about Unicode characters you can use ASCII to build the structures, so your example structure becomes</p> <pre><code>. +-- _config.yml +-- _drafts | +-- begin-with-the-crazy-ideas.textile | +-- on-simplicity-in-technology.markdown +-- _includes | +-- footer.html | +-- header.html +-- _layouts | +-- default.html | +-- post.html +-- _posts | +-- 2007-10-29-why-every-programmer-should-play-nethack.textile | +-- 2009-04-26-barcamp-boston-4-roundup.textile +-- _data | +-- members.yml +-- _site +-- index.html </code></pre> <p>Which is similar to the format <code>tree</code> uses if you select <code>ANSI</code> output.</p>
1,247,894
Coroutines for game design?
<p>I've heard that coroutines are a good way to structure games (e.g., <a href="http://www.python.org/dev/peps/pep-0342/" rel="noreferrer">PEP 342</a>: "Coroutines are a natural way of expressing many algorithms, such as simulations, games...") but I'm having a hard time wrapping my head around how this would actually be done.</p> <p>I see from this <a href="http://www.ibm.com/developerworks/library/l-pygen.html" rel="noreferrer">article</a> that coroutines can represent states in a state machine which transition to each other using a scheduler, but it's not clear to me how this applies to a game where the game state is changing based on moves from multiple players.</p> <p>Is there any simple example of a game written using coroutines available? Or can someone offer a sketch of how it might be done?</p>
1,247,990
5
0
null
2009-08-08 03:31:01.367 UTC
13
2013-03-12 10:13:21.043 UTC
null
null
null
null
49,559
null
1
16
python|coroutine
3,941
<p>One way coroutines can be used in games is as light weight threads in an actor like model, like in <a href="http://www.kamaelia.org/Home" rel="noreferrer">Kamaelia</a>.</p> <p>Each object in your game would be a Kamaelia 'component'. A component is an object that can pause execution by yielding when it's allowable to pause. These components also have a messaging system that allows them to safely communicate to each other asynchronously.</p> <p>All the objects would be concurrently doing their own thing, with messages sent to each other when interactions occur.</p> <p>So, it's not really specific to games, but anything when you have a multitude of communicating components acting concurrently could benefit from coroutines.</p>
425,077
how to delete the pluginassembly after AppDomain.Unload(domain)
<p>i have a weird problem. i would like to delete an assembly(plugin.dll on harddisk) which is already loaded, but the assembly is locked by the operating system (vista), even if i have unloaded it. </p> <p>f.e.</p> <pre><code>AppDomainSetup setup = new AppDomainSetup(); setup.ShadowCopyFiles = "true"; AppDomain appDomain = AppDomain.CreateDomain(assemblyName + "_AppDomain", AppDomain.CurrentDomain.Evidence, setup); IPlugin plugin = (IPlugin)appDomain.CreateInstanceFromAndUnwrap(assemblyName, "Plugin.MyPlugins"); </code></pre> <p>I also need the assemblyinfos, because I don't know which classes in the pluginassembly implements the IPlugin Interface. It should be possible to have more than one Plugin in one Pluginassembly.</p> <pre><code>Assembly assembly = appDomain.Load(assemblyName); if (assembly != null) { Type[] assemblyTypes = assembly.GetTypes(); foreach (Type assemblyTyp in assemblyTypes) { if (typeof(IPlugin).IsAssignableFrom(assemblyTyp)) { IPlugin plugin = (IPlugin)Activator.CreateInstance(assemblyTyp); plugin.AssemblyName = assemblyNameWithEx; plugin.Host = this; } } } AppDomain.Unload(appDomain); </code></pre> <p>How is it possible to get the assemblyinfos from the appDomain without locking the assembly? </p> <p>best regards</p>
435,974
5
0
null
2009-01-08 17:10:37.753 UTC
11
2012-02-29 22:27:14.33 UTC
2009-04-25 10:05:46.65 UTC
Ase
49,246
Ase
52,418
null
1
18
c#|plugins|assemblies
8,995
<p>I think i've the answer! the answer from Øyvind Skaar will not work, if you would like to delete the loaded assembly.</p> <p>instead of </p> <pre><code>using (FileStream dll = File.OpenRead(path)) { fileContent = new byte[dll.Length]; dll.Read(fileContent, 0, (int)dll.Length); } Assembly assembly = appDomain.Load(fileContent); </code></pre> <p>you have to use</p> <pre><code>byte[] b = File.ReadAllBytes(assemblyName); assembly = Assembly.Load(b); </code></pre> <p>best regards</p>
316,488
Bit mask in C
<p>What is the best way to construct a bit mask in C with <code>m</code> set bits preceded by <code>k</code> unset bits, and followed by <code>n</code> unset bits:</p> <pre><code>00..0 11..1 00..0 k m n </code></pre> <p>For example, k=1, m=4, n=3 would result in the bit mask:</p> <pre><code>01111000 </code></pre>
316,493
5
4
null
2008-11-25 06:16:37.14 UTC
16
2022-04-08 12:25:25.287 UTC
2008-11-25 06:38:55.63 UTC
Robert Gamble
25,222
grigy
1,692,070
null
1
23
c|bit-manipulation
41,437
<p>You can do:</p> <pre><code>~(~0 &lt;&lt; m) &lt;&lt; n </code></pre>
782,178
How do I convert a String to an InputStream in Java?
<p>Given a string:</p> <pre><code>String exampleString = "example"; </code></pre> <p>How do I convert it to an <code>InputStream</code>?</p>
782,183
5
1
2009-04-23 15:11:23.667 UTC
2009-04-23 15:11:23.667 UTC
124
2021-02-28 06:34:18.097 UTC
2015-07-29 14:59:54.667 UTC
null
4,277,762
null
5,993
null
1
973
java|string|type-conversion|inputstream
744,450
<p>Like this:</p> <pre><code>InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8)); </code></pre> <p>Note that this assumes that you want an InputStream that is a stream of bytes that represent your original string encoded as <em>UTF-8</em>.</p> <p>For versions of Java less than 7, replace <code>StandardCharsets.UTF_8</code> with <code>"UTF-8"</code>.</p>
1,212,605
How to search Array for multiple values in PHP?
<p>I need to get the keys from values that are duplicates. I tried to use array_search and that worked fine, BUT I only got the first value as a hit.</p> <p>I need to get both keys from the duplicate values, in this case 0 and 2. The search result output as an array would be good.</p> <p>Is there a PHP function to do this or do I need to write some multiple loops to do it?</p> <pre><code>$list[0][0] = "2009-09-09"; $list[0][1] = "2009-05-05"; $list[0][2] = "2009-09-09"; $list[1][0] = "first-paid"; $list[1][1] = "1"; $list[1][2] = "last-unpaid"; echo array_search("2009-09-09",$list[0]); </code></pre>
1,212,641
6
0
null
2009-07-31 13:42:19.34 UTC
3
2021-06-19 12:36:48.363 UTC
2017-03-03 16:05:10.22 UTC
null
55,075
null
148,496
null
1
23
php|arrays|search|duplicates|key
83,191
<p>You want <a href="http://tr.php.net/manual/en/function.array-keys.php" rel="noreferrer">array_keys</a> with the search value</p> <pre><code>array_keys($list[0], "2009-09-09"); </code></pre> <p>which will return an array of the keys with the specified value, in your case [0, 2]. If you want to find the duplicates as well, you can first make a pass with <a href="http://uk3.php.net/manual/en/function.array-unique.php" rel="noreferrer">array_unique</a>, then iterate over that array using array_keys on the original; anything which returns an array of length > 1 is a duplicate, and the result is the keys in which the duplicates are stored. Something like...</p> <pre><code>$uniqueKeys = array_unique($list[0]) foreach ($uniqueKeys as $uniqueKey) { $v = array_keys($list[0], $uniqueKey); if (count($v) &gt; 1) { foreach ($v as $key) { // Work with $list[0][$key] } } } </code></pre>
217,980
C# little endian or big endian?
<p>In the documentation of hardware that allows us to control it via UDP/IP, I found the following fragment:</p> <blockquote> <p>In this communication protocol, DWORD is a 4 bytes data, WORD is a 2 bytes data, BYTE is a single byte data. The storage format is little endian, namely 4 bytes (32bits) data is stored as: d7-d0, d15-d8, d23-d16, d31-d24; double bytes (16bits) data is stored as: d7-d0 , d15-d8.</p> </blockquote> <p>I am wondering how this translates to C#? Do I have to convert stuff before sending it over? For example, if I want to send over a 32 bit integer, or a 4 character string?</p>
217,993
6
0
null
2008-10-20 10:13:25.883 UTC
23
2015-09-10 20:25:11.107 UTC
2009-03-26 22:59:03.187 UTC
Rich B
5,640
TimothyP
28,149
null
1
68
c#|hardware|udp|endianness
109,939
<p>C# itself doesn't define the endianness. Whenever you convert to bytes, however, you're making a choice. The <a href="http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx" rel="noreferrer">BitConverter</a> class has an <a href="http://msdn.microsoft.com/en-us/library/system.bitconverter.islittleendian.aspx" rel="noreferrer">IsLittleEndian</a> field to tell you how it will behave, but it doesn't give the choice. The same goes for BinaryReader/BinaryWriter.</p> <p>My <a href="http://pobox.com/~skeet/csharp/miscutil" rel="noreferrer">MiscUtil</a> library has an EndianBitConverter class which allows you to define the endianness; there are similar equivalents for BinaryReader/Writer. No online usage guide I'm afraid, but they're trivial :)</p> <p>(EndianBitConverter also has a piece of functionality which isn't present in the normal BitConverter, which is to do conversions in-place in a byte array.)</p>
58,743,333
React app stuck on "Starting the development server"
<p>I have a react app created by create-react-app. After running npm start (the start script is present in package.json as "start": "react-scripts start") the console says Starting the development server as usual and fires up the browser. But after this both the console and the browser do absolutely nothing indefinitely. No error or output. It simply does nothing.</p>
59,831,823
22
13
null
2019-11-07 06:48:54.083 UTC
5
2022-06-04 04:12:28.217 UTC
null
null
null
null
12,043,177
null
1
66
reactjs|npm|create-react-app|react-scripts
69,706
<p>I have something similar happening to me.</p> <p>I have a react project that I want to convert to Typescript and I started as you noted with the "create-react-app", added all my files and hoped for the best - but got stuck like you on the “Starting the development server” message.</p> <p>I have an 8GB Ram with Windows 10 and once I used the default "npm start" for the first time I've seen the node process uses a lot of memory - So I tried to give it more and at the same time I tired to change the port react uses.</p> <ol> <li><p>Added this to the start script in package.json:</p> <p><code>"scripts": { "start": "PORT=3001 react-scripts --max_old_space_size=8128 start", ... }</code></p></li> <li><p>Closed all my chrome browsers (they take pretty much memory)</p></li> <li>And gave it around 1 minute to run</li> </ol> <p>After 1 minute it started working and from that point it just starts quickly and not uses as much memory and not depended on the port I choose</p> <p>In my case - I guess the first time you run "npm start" on the React Typescript project it probably index the files (or does something similar - I'm not sure and probably need to read about it - I'm new to typescript) which take a lot of memory.</p> <p>In your case - It might be something similar</p> <p>Hope it helps :)</p>
32,464,829
Error : length of 'dimnames' [2] not equal to array extent
<p>I have changed a little bit my R code that worked perfectly,but instead 3 now I have 7 clusters.</p> <pre><code>layout(matrix(c(1, 1, 2, 2, 3, 3, 4, 4, 5), ncol=1)) # main plots par(mai=rep(0.5, 4)) fcm &lt;-c(14.0,14.1,13.0,14.2,14.7,13.8,14.0) gk &lt;-c(12.1,12.5,12.2,12.0,11.5,12.0,11.4) gg &lt;-c(14.0,14.1,13.3,12.8,12.0,12.2,12.0) data1 &lt;- rbind(fcm,gk,gg) colnames(data1) &lt;- c(6,7,8,9,10,11,12) fcm &lt;-c(2.65,2.55,2.4,2.45,2.45,2.5,2.45) gk &lt;-c(2.45,2.55,2.4,2.3,2.2,2.35,2.1) gg &lt;-c(2.6,2.65,2.5,2.35,2.4,2.4,2.2) data2 &lt;- rbind(fcm,gk,gg) colnames(data2) &lt;- c(6,7,8,9,10,11,12) fcm &lt;-c(8.8,6.5,6.6,8.2,8.0,8.4,9.0) gk &lt;-c(12.7,11.0,11.1,10.5,10.7,10.0,9.5) gg &lt;-c(2.1,2.1,1.8,2.0,2.0,1.9,1.8) data3 &lt;- rbind(fcm,gk,gg) colnames(data3) &lt;- c(6,7,8,9,10,11,12) fcm &lt;-c(0.47,0.53,0.45,0.39,0.40,0.47,0.48) gk &lt;-c(0.45,0.51,0.34,0.40,0.42,0.42,0.44) data4 &lt;- rbind(fcm,gk) colnames(data4) &lt;- c(6,7,8,9,10,11,12) barplot(as.matrix(data1),ylim=c(0,20),main="P wave", xlab="number of clusters", ylab="traveltime rms(ms)", col=c("red", "black", "green"), beside=TRUE) barplot(as.matrix(data2),ylim=c(0,2),main="MT", xlab="number of clusters", ylab="MT functions", col=c("red", "black", "green"), beside=TRUE) barplot(as.matrix(data3),ylim=c(0,20),main="XBI", xlab="number of clusters", ylab="index value", col=c("red", "black", "green"), beside=TRUE) barplot(as.matrix(data4),ylim=c(0,0.6),main="NCE", xlab="number of clusters", ylab="index value", col=c("red", "black"), beside=TRUE) par(mai=c(0,0,0,0)) plot.new() legend(legend = c("fcm","gk","gg"), fill = c( "red", "black", "green"), "center", horiz=TRUE) </code></pre> <p>But then I got</p> <pre><code>Error in `colnames&lt;-`(`*tmp*`, value = c(6, 7, 8, 9, 10, 11, 12)) : length of 'dimnames' [2] not equal to array extent </code></pre> <p>The problem is with the rbind.I am combining 3 vectors,each of them has 7 elements.What should I change?I want that each element has the proper number of clusters labeled behind.</p>
32,464,998
1
6
null
2015-09-08 18:29:48.947 UTC
1
2015-09-09 17:15:13.1 UTC
2015-09-09 17:15:13.1 UTC
null
4,723,732
null
4,723,732
null
1
13
r
89,242
<p>You need to supply one more column name. Your data has eight columns, as can be seen, e.g., with</p> <pre><code>&gt; length(fcm) [1] 8 </code></pre> <p>or</p> <pre><code>&gt; ncol(data1) [1] 8 </code></pre> <p>or by displaying the matrix:</p> <pre><code>&gt; data1 # [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] #fcm 14.0 14.1 13.0 14 2.0 14.7 13.8 14.0 #gk 12.1 12.5 12.2 12 0.0 11.5 12.0 11.4 #gg 14.0 14.1 13.0 3 12.8 12.0 12.2 12.0 </code></pre> <p>while </p> <pre><code>&gt; length( c(6, 7, 8, 9, 10, 11, 12)) [1] 7 </code></pre> <p>You could try with </p> <pre><code>colnames(data1) &lt;- c(6:13) </code></pre> <p>With your data, this would be:</p> <pre><code>fcm &lt;-c(14.0,14.1,13.0,14,2,14.7,13.8,14.0) gk &lt;-c(12.1,12.5,12.2,12,0,11.5,12.0,11.4) gg &lt;-c(14.0,14.1,13,3,12.8,12.0,12.2,12.0) data1 &lt;- rbind(fcm,gk,gg) colnames(data1) &lt;- c(6:13) </code></pre> <p>which gives:</p> <pre><code>&gt; data1 6 7 8 9 10 11 12 13 fcm 14.0 14.1 13.0 14 2.0 14.7 13.8 14.0 gk 12.1 12.5 12.2 12 0.0 11.5 12.0 11.4 gg 14.0 14.1 13.0 3 12.8 12.0 12.2 12.0 </code></pre> <p>without any error message.</p>
21,204,305
rerendering events in fullCalendar after Ajax database update
<p>I am trying to have fullCalendar reflect changes made to a database via AJAX. The problem is that it won't update the calendar on screen after a successful AJAX call.</p> <pre><code>$.ajax({ type: "POST", url: "eventEditXHR.php", data: { //the data }, success: function(text) { $("#calendar").fullCalendar("refetchEvents"); }.... </code></pre> <p>I'm I using the wrong method? What would be the best way to accomplish this without having to reload the whole page? Thanks for any input! </p>
21,265,248
8
4
null
2014-01-18 12:48:36.343 UTC
13
2021-02-11 15:12:32.843 UTC
null
null
null
null
2,743,389
null
1
23
javascript|jquery|ajax|fullcalendar
93,993
<p>There are several ways. Some less elegant.</p> <h3>1. If you are using FullCalendar to grab json events:</h3> <pre><code>$('#calendar').fullCalendar({ events: "json-events.php", }); </code></pre> <p>Just do:</p> <pre><code>$('#calendar').fullCalendar( 'refetchEvents' ); </code></pre> <h3>If you want outside method to fetch events you could do. Not elegant but will work</h3> <pre><code>$('#calendar').fullCalendar( 'removeEventSource', source ) $('#calendar').fullCalendar( 'addEventSource', source ) </code></pre>
44,202,700
Spring @Cacheable default TTL
<p>I generally use the <code>@Cacheable</code> with a cache config in my spring-boot app and set specific TTL (time to live) for each cache.</p> <p>I recently inherited a spring boot app that uses <code>@Cacheable</code> without explicitly stating a cache manager and ttl. I will be changing it to be explicit.</p> <p>But I am not able to find out what are the defaults when there is nothing explicit.</p> <p>I did look at the <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/cache/annotation/Cacheable.html" rel="noreferrer">docs</a> but found nothing there</p>
44,205,512
5
1
null
2017-05-26 13:20:34.81 UTC
5
2020-09-16 19:14:53.057 UTC
2020-09-16 19:14:53.057 UTC
null
666,414
null
226,906
null
1
16
spring|spring-boot|caching|spring-cache
52,912
<p><em>Spring</em> is pretty clear about TTL/TTI (Expiration) and Eviction policies as explained in the core <em>Spring Framework Reference Guide</em> <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#cache-specific-config" rel="noreferrer">here</a>. In other words, the "defaults" depend entirely on the underlying data store (a.k.a. caching provider) used with the <em>Spring Boot</em> app via the <em>Spring Cache Abstraction</em>.</p> <p>While <strong>Arpit's</strong> solution is a nice workaround and a generic, transferable solution across different caching providers (data stores), it also cannot cover more specific expiration/eviction policies, such as the kind of action to perform when an expiration/eviction, say OVERFLOW_TO_DISK, or LOCAL_DESTROY only (such as in a Highly Available (maybe zoned based), distributed scenario), or INVALIDATE, etc.</p> <p>Usually, depending on the UC, evicting "all" entries is not an acceptable option and is one of the reasons why <em>Spring</em> delegates this responsibility to caching provider as this capability varies highly between 1 provider to another.</p> <p>In summary... definitely review the requirements for your UC and pair the appropriate caching provider with the capabilities that match your UC. <em>Spring</em> <a href="http://docs.spring.io/spring-boot/docs/1.5.3.RELEASE/reference/htmlsingle/#_supported_cache_providers" rel="noreferrer">supports a wide variety of caching providers</a> from <a href="http://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#redis:support:cache-abstraction" rel="noreferrer">Redis</a> to <a href="http://docs.spring.io/spring-data-gemfire/docs/current/reference/html/#apis:spring-cache-abstraction" rel="noreferrer">Apache Geode/Pivotal GemFire</a> to <em>Hazelcast</em>, etc, each with different/similar capabilities in this regard.</p>
44,099,851
How do I pass variables between stages in a declarative Jenkins pipeline?
<p>How do I pass variables between stages in a declarative pipeline?</p> <p>In a scripted pipeline, I gather the procedure is to write to a temporary file, then read the file into a variable.</p> <p>How do I do this in a declarative pipeline?</p> <p>E.g. I want to trigger a build of a different job, based on a variable created by a shell action.</p> <pre><code>stage("stage 1") { steps { sh "do_something &gt; var.txt" // I want to get var.txt into VAR } } stage("stage 2") { steps { build job: "job2", parameters[string(name: "var", value: "${VAR})] } } </code></pre>
44,101,004
4
2
null
2017-05-21 17:35:11.593 UTC
25
2022-05-26 05:09:40.43 UTC
null
null
null
null
272,023
null
1
113
jenkins|jenkins-pipeline
149,921
<p>If you want to use a file (since a script is the thing generating the value you need), you could use <code>readFile</code> as seen below. If not, use <code>sh</code> with the <code>script</code> option as seen below:</p> <pre><code>// Define a groovy local variable, myVar. // A global variable without the def, like myVar = 'initial_value', // was required for me in older versions of jenkins. Your mileage // may vary. Defining the variable here maybe adds a bit of clarity, // showing that it is intended to be used across multiple stages. def myVar = 'initial_value' pipeline { agent { label 'docker' } stages { stage('one') { steps { echo &quot;1.1. ${myVar}&quot; // prints '1.1. initial_value' sh 'echo hotness &gt; myfile.txt' script { // OPTION 1: set variable by reading from file. // FYI, trim removes leading and trailing whitespace from the string myVar = readFile('myfile.txt').trim() } echo &quot;1.2. ${myVar}&quot; // prints '1.2. hotness' } } stage('two') { steps { echo &quot;2.1 ${myVar}&quot; // prints '2.1. hotness' sh &quot;echo 2.2. sh ${myVar}, Sergio&quot; // prints '2.2. sh hotness, Sergio' } } // this stage is skipped due to the when expression, so nothing is printed stage('three') { when { expression { myVar != 'hotness' } } steps { echo &quot;three: ${myVar}&quot; } } } } </code></pre>