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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
17,516,820 | Serving files stored in S3 in express/nodejs app | <p>I have app where user's photos are private. I store the photos(thumbnails also) in AWS s3. There is a page in the site where user can view his photos(i.e thumbnails). Now my problem is how do I serve these files. Some options that I have evaluated are:</p>
<ul>
<li>Serving files from CloudFront(or AWS) using signed url generation. But the problem is every time the user refreshes the page I have to create so many signed urls again and load it. So therefore I wont be able to cache the Images in the browser which would have been a good choice. Is there anyway to do still in javascript? I cant have the validity of those urls for longer due to security issues. And secondly within that time frame if someone got hold of that url he can view the file without running through authentication from the app.</li>
<li>Other option is to serve the file from my express app itself after streaming it from S3 servers. This allows me to have http cache headers, therefore enable browser caching. It also makes sure no one can view a file without being authenticated. Ideally I would like to stream the file and a I am hosting using NGINX proxy relay the other side streaming to NGINX. But as i see that can only be possible if the file exist in the same system's files. But here I have to stream it and return when i get the stream is complete. Don't want to store the files locally.</li>
</ul>
<p>I am not able to evaluate which of the two options would be a better choice?? I want to redirect as much work as possible to S3 or cloudfront but even using singed urls also makes the request first to my servers. I also want caching features. </p>
<p>So what would be ideal way to do? with the answers for the particular questions pertaining to those methods?</p> | 17,638,498 | 4 | 0 | null | 2013-07-07 22:00:06.837 UTC | 13 | 2016-02-17 21:24:06.107 UTC | 2016-02-17 21:24:06.107 UTC | null | 324,243 | null | 1,624,106 | null | 1 | 21 | node.js|nginx|amazon-s3|express|fileserver | 16,825 | <p>i would just stream it from S3. it's very easy, and signed URLs are much more difficult. just make sure you set the <code>content-type</code> and <code>content-length</code> headers when you upload the images to S3. </p>
<pre><code>var aws = require('knox').createClient({
key: '',
secret: '',
bucket: ''
})
app.get('/image/:id', function (req, res, next) {
if (!req.user.is.authenticated) {
var err = new Error()
err.status = 403
next(err)
return
}
aws.get('/image/' + req.params.id)
.on('error', next)
.on('response', function (resp) {
if (resp.statusCode !== 200) {
var err = new Error()
err.status = 404
next(err)
return
}
res.setHeader('Content-Length', resp.headers['content-length'])
res.setHeader('Content-Type', resp.headers['content-type'])
// cache-control?
// etag?
// last-modified?
// expires?
if (req.fresh) {
res.statusCode = 304
res.end()
return
}
if (req.method === 'HEAD') {
res.statusCode = 200
res.end()
return
}
resp.pipe(res)
})
})
</code></pre> |
17,411,991 | HTML5 Canvas Rotate Image | <pre><code>jQuery('#carregar').click(function() {
var canvas = document.getElementById('canvas');
var image = document.getElementById('image');
var element = canvas.getContext("2d");
element.clearRect(0, 0, canvas.width, canvas.height);
element.drawImage(image, 0, 0, 300, 300);
});
</code></pre>
<p><a href="http://jsfiddle.net/braziel/nWyDE/" rel="noreferrer">jsfiddle.net/braziel/nWyDE/</a></p>
<p>I have a problem to rotate an image 90 ° to the right or to the left.</p>
<p>I use an image on the canvas, the same screen will have several canvas equal to that of the example, but I left it as close as possible to the project.</p>
<p>I ask, how do I rotate the image 90 ° to the left or right when I click "Rotate Left" and "Rotate Right"?</p>
<p>I tried several codes on the internet but none worked.</p> | 17,412,387 | 11 | 0 | null | 2013-07-01 19:15:50.55 UTC | 34 | 2021-05-30 22:15:55.413 UTC | 2020-11-29 11:47:08.95 UTC | null | 863,110 | null | 2,540,084 | null | 1 | 88 | html|image|canvas|rotation|html5-canvas | 206,063 | <p><strong>You can use canvas’ context.translate & context.rotate to do rotate your image</strong></p>
<p><img src="https://i.stack.imgur.com/hwxO6.png" alt="enter image description here"></p>
<p>Here’s a function to draw an image that is rotated by the specified degrees:</p>
<pre><code>function drawRotated(degrees){
context.clearRect(0,0,canvas.width,canvas.height);
// save the unrotated context of the canvas so we can restore it later
// the alternative is to untranslate & unrotate after drawing
context.save();
// move to the center of the canvas
context.translate(canvas.width/2,canvas.height/2);
// rotate the canvas to the specified degrees
context.rotate(degrees*Math.PI/180);
// draw the image
// since the context is rotated, the image will be rotated also
context.drawImage(image,-image.width/2,-image.width/2);
// we’re done with the rotating so restore the unrotated context
context.restore();
}
</code></pre>
<p>Here is code and a Fiddle: <a href="http://jsfiddle.net/m1erickson/6ZsCz/" rel="noreferrer">http://jsfiddle.net/m1erickson/6ZsCz/</a></p>
<pre><code><!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var angleInDegrees=0;
var image=document.createElement("img");
image.onload=function(){
ctx.drawImage(image,canvas.width/2-image.width/2,canvas.height/2-image.width/2);
}
image.src="houseicon.png";
$("#clockwise").click(function(){
angleInDegrees+=30;
drawRotated(angleInDegrees);
});
$("#counterclockwise").click(function(){
angleInDegrees-=30;
drawRotated(angleInDegrees);
});
function drawRotated(degrees){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(canvas.width/2,canvas.height/2);
ctx.rotate(degrees*Math.PI/180);
ctx.drawImage(image,-image.width/2,-image.width/2);
ctx.restore();
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas><br>
<button id="clockwise">Rotate right</button>
<button id="counterclockwise">Rotate left</button>
</body>
</html>
</code></pre> |
9,836,375 | creating a horizontal colored strip using css | <p>In my webpage I need to put a horizontal colored strip of some width just beneath a Logo text. </p>
<p>I tried to use this css:</p>
<pre><code>#colorstrip{
width: 100%; height: 2px;
border-style: solid;
border-color: white;
}
</code></pre>
<p>with this html:</p>
<pre><code><span id="logo"> My site</span>
<div id="colorstrip"/>
</code></pre>
<p>But it shows a white rectangle. How do I make it a filled one? Or do I have to use an image (may be a white square) and put it as background of the div with repeat?</p>
<p>Is using a div for showing this thin bar the correct way?
What do you advise?</p> | 9,836,405 | 4 | 1 | null | 2012-03-23 08:59:54.487 UTC | 2 | 2015-10-21 05:35:16.99 UTC | 2015-10-21 05:35:16.99 UTC | null | 3,102,264 | null | 879,104 | null | 1 | 4 | html|css | 58,658 | <p>if you want to fill it, use:</p>
<pre><code>#colorstrip{
width: 100%; height: 2px;
border-style: solid;
border-color: white;
background-color: white;
}
</code></pre> |
23,183,507 | Outline object (normal scale + stencil mask) three.js | <p>For some time, I've been trying to figure out how to do an object selection outline in my game. (So the player can see the object over everything else, on mouse-over)</p>
<p>This is how the result should look:</p>
<p><img src="https://i.stack.imgur.com/UM3lc.png" alt="enter image description here"></p>
<p>The solution I would like to use goes like this:</p>
<ol>
<li>Layer 1: Draw model in regular shading.</li>
<li>Layer 2: Draw a copy in red color, scaled along normals using vertex shader.</li>
<li>Mask: Draw a black/white flat color of the model to use it as a stencil mask for the second layer, to hide insides and show layer 1.</li>
</ol>
<p>And here comes the problem. I can't really find any good learning materials about masks. Can I subtract the insides from the outline shape? What am I doing wrong?</p>
<p>I can't figure out how to stack my render passes to make the mask work. :(</p>
<p><strong>Here's a <a href="http://jsfiddle.net/Eskel/g593q/4/" rel="noreferrer">jsfiddle demo</a></strong></p>
<pre><code>renderTarget = new THREE.WebGLRenderTarget(window.innerWidth, window.innerHeight, renderTargetParameters)
composer = new THREE.EffectComposer(renderer, renderTarget)
// composer = new THREE.EffectComposer(renderer)
normal = new THREE.RenderPass(scene, camera)
outline = new THREE.RenderPass(outScene, camera)
mask = new THREE.MaskPass(maskScene, camera)
// mask.inverse = true
clearMask = new THREE.ClearMaskPass
copyPass = new THREE.ShaderPass(THREE.CopyShader)
copyPass.renderToScreen = true
composer.addPass(normal)
composer.addPass(outline)
composer.addPass(mask)
composer.addPass(clearMask)
composer.addPass(copyPass)
</code></pre>
<p>Also I have no idea whether to use render target or renderer for the source of the composer. :( Should I have the first pass in the composer at all? Why do I need the copy pass? So many questions, I know. But there are just not enough resources to learn from, I've been googling for days.</p>
<p>Thanks for any advice!</p> | 23,198,184 | 2 | 5 | null | 2014-04-20 14:22:35.737 UTC | 8 | 2014-05-18 11:21:03.883 UTC | 2014-04-20 15:35:22.343 UTC | null | 3,163,669 | null | 3,163,669 | null | 1 | 11 | three.js|webgl | 12,955 | <p>Here's a js fiddle with working solution. You're welcome. :)</p>
<p><a href="http://jsfiddle.net/Eskel/g593q/5/" rel="noreferrer">http://jsfiddle.net/Eskel/g593q/6/</a></p>
<p>Update with only two render passes (credit to WestLangley):
<a href="http://jsfiddle.net/Eskel/g593q/9/" rel="noreferrer">http://jsfiddle.net/Eskel/g593q/9/</a> </p>
<p>The pieces missing were these:</p>
<pre><code>composer.renderTarget1.stencilBuffer = true
composer.renderTarget2.stencilBuffer = true
outline.clear = false
</code></pre> |
23,247,125 | Cannot convert lambda expression to type 'object' because it is not a delegate type | <p>I have a base class that has a bool property which looks like this:</p>
<pre><code>public abstract class MyBaseClass
{
public bool InProgress { get; protected set; }
}
</code></pre>
<p>I am inheriting it another class from it and trying to add InProgress as a delegate to the dictionary. But it throws me an error. This is how my Derived class looks like:</p>
<pre><code>public abstract class MyClass
{
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("InProgress", InProgress => base.InProgress = InProgress);
}
</code></pre>
<p>This is the error I am getting:</p>
<blockquote>
<p>Cannot convert lambda expression to type 'object' because it is not a delegate type</p>
</blockquote>
<p>What am I doing wrong here?</p> | 23,247,231 | 5 | 6 | null | 2014-04-23 14:16:58.99 UTC | 1 | 2020-09-14 06:34:45.903 UTC | 2017-07-25 10:35:19.357 UTC | null | 271,200 | null | 395,255 | null | 1 | 54 | c#|linq|lambda|delegates | 113,622 | <p>Best would be to have the dictionary strongly typed, but if you assign the lambda to a specific lambda (delegate) first, it should work (because the compiler then knows the delegate format):</p>
<pre><code>Action<bool> inp = InProgress => base.InProgress = InProgress;
dict.Add("InProgress", inp);
</code></pre>
<p><em>Or</em> by casting it directly, same effect</p>
<pre><code>dict.Add("InProgress", (Action<bool>)(InProgress => base.InProgress = InProgress));
</code></pre>
<p>Of course having such a dictionary format as object is discussable, since you'll have to know the delegate format to be able to use it.</p> |
5,399,601 | ImageSourceConverter error for Source=null | <p>I'm binding the Source property of an Image to a string. This string may be null in which case I just don't want to display an Image. However, I'm getting the following in my Debug output:</p>
<blockquote>
<p>System.Windows.Data Error: 23 : Cannot
convert '<null>' from type '<null>' to
type
'System.Windows.Media.ImageSource' for
'en-AU' culture with default
conversions; consider using Converter
property of Binding.
NotSupportedException:'System.NotSupportedException:
ImageSourceConverter cannot convert
from (null). at
System.ComponentModel.TypeConverter.GetConvertFromException(Object
value) at
System.Windows.Media.ImageSourceConverter.ConvertFrom(ITypeDescriptorContext
context, CultureInfo culture, Object
value) at
MS.Internal.Data.DefaultValueConverter.ConvertHelper(Object
o, Type destinationType,
DependencyObject targetElement,
CultureInfo culture, Boolean
isForward)'</p>
</blockquote>
<p>I'd prefer if this wasn't displayed as it's just noise - is there any way to suppress it?</p> | 5,628,347 | 3 | 2 | null | 2011-03-23 00:39:57.72 UTC | 9 | 2020-10-13 14:58:04.317 UTC | 2012-05-10 15:08:43.647 UTC | null | 41,956 | null | 652,715 | null | 1 | 56 | .net|wpf|image|exception-handling|ivalueconverter | 21,783 | <p>@AresAvatar is right in suggesting you use a ValueConverter, but that implementation does not help the situation. This does:</p>
<pre><code>public class NullImageConverter :IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return DependencyProperty.UnsetValue;
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// According to https://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.convertback(v=vs.110).aspx#Anchor_1
// (kudos Scott Chamberlain), if you do not support a conversion
// back you should return a Binding.DoNothing or a
// DependencyProperty.UnsetValue
return Binding.DoNothing;
// Original code:
// throw new NotImplementedException();
}
}
</code></pre>
<p>Returning <code>DependencyProperty.UnsetValue</code> also addresses the performance issues from throwing (and ignoring) all those exceptions. Returning a <code>new BitmapSource(uri)</code> would also get rid of the exceptions, but there is still a performance hit (and it isn't necessary).</p>
<p>Of course, you'll also need the plumbing:</p>
<p>In resources:</p>
<pre><code><local:NullImageConverter x:Key="nullImageConverter"/>
</code></pre>
<p>Your image:</p>
<pre><code><Image Source="{Binding Path=ImagePath, Converter={StaticResource nullImageConverter}}"/>
</code></pre> |
9,521,651 | R and object oriented programming | <p>Object oriented programming in one way or another is very much possible in R. However, unlike for example Python, there are many ways to achieve object orientation:</p>
<ul>
<li>The <a href="http://cran.r-project.org/web/packages/R.oo/index.html">R.oo package</a></li>
<li>S3 and S4 classes</li>
<li><a href="http://search.r-project.org/library/methods/html/refClass.html">Reference classes</a></li>
<li>the <a href="http://cran.r-project.org/web/packages/proto/index.html">proto package</a></li>
</ul>
<p>My question is:</p>
<p>What <strong>major</strong> differences distinguish these ways of OO programming in R?</p>
<p>Ideally the answers here will serve as a reference for R programmers trying to decide which OO programming methods best suits their needs. </p>
<p>As such, I am asking for detail, presented in an objective manner, based on experience, and backed with facts and reference. Bonus points for clarifying <em>how</em> these methods map to standard OO practices.</p> | 9,522,858 | 3 | 4 | null | 2012-03-01 18:16:25.687 UTC | 56 | 2014-07-25 13:53:11.5 UTC | 2012-03-05 15:43:55.297 UTC | user1228 | null | null | 1,033,808 | null | 1 | 81 | oop|r | 44,296 | <p><strong>S3 classes</strong></p>
<ul>
<li>Not really objects, more of a naming convention</li>
<li>Based around the . syntax: E.g. for print, <code>print</code> calls <code>print.lm</code> <code>print.anova</code>, etc. And if not found,<code>print.default</code></li>
</ul>
<p><strong>S4 classes</strong></p>
<ul>
<li><a href="https://stackoverflow.com/questions/6450803/class-in-r-s3-vs-s4">Can dispatch on multiple arguments</a></li>
<li>More complicated to implement than S3</li>
</ul>
<p><strong>Reference classes</strong></p>
<ul>
<li>Primarily useful to avoid making copies of large objects (pass by reference)</li>
<li><a href="https://stackoverflow.com/questions/5137199/what-is-the-significance-of-the-new-reference-classes">Description of reasons to use RefClasses</a></li>
</ul>
<p><strong>proto</strong></p>
<ul>
<li>ggplot2 was originally written in proto, but will eventually be rewritten using S3.</li>
<li>Neat concept (prototypes, not classes), but seems tricky in practice</li>
<li>Next version of ggplot2 seems to be moving away from it</li>
<li><a href="http://cran.r-project.org/web/packages/proto/vignettes/proto.pdf" rel="noreferrer">Description of the concept and implementation</a></li>
</ul>
<p><strong>R6 classes</strong></p>
<ul>
<li><a href="http://cran.r-project.org/web/packages/R6/vignettes/Introduction.html" rel="noreferrer">By-reference</a></li>
<li>Does not depend on S4 classes</li>
<li>"<a href="http://rpubs.com/wch/17459" rel="noreferrer">Creating</a> an R6 class is similar to the reference class, except that there’s no need to separate the fields and methods, and you can’t specify the types of the fields."</li>
</ul> |
60,241,857 | java.lang.UnsupportedOperationException: Reflective setAccessible(true) disabled | <p>When I run my Ktor application with <code>gradle run</code> then I've got the following exception: </p>
<pre><code>19:21:11.795 [main] DEBUG io.netty.util.internal.logging.InternalLoggerFactory - Using SLF4J as the default logging framework
19:21:11.810 [main] DEBUG io.netty.util.internal.PlatformDependent0 - -Dio.netty.noUnsafe: false
19:21:11.810 [main] DEBUG io.netty.util.internal.PlatformDependent0 - Java version: 11
19:21:11.811 [main] DEBUG io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.theUnsafe: available
19:21:11.812 [main] DEBUG io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.copyMemory: available
19:21:11.812 [main] DEBUG io.netty.util.internal.PlatformDependent0 - java.nio.Buffer.address: available
19:21:11.814 [main] DEBUG io.netty.util.internal.PlatformDependent0 - direct buffer constructor: unavailable
java.lang.UnsupportedOperationException: Reflective setAccessible(true) disabled
at io.netty.util.internal.ReflectionUtil.trySetAccessible(ReflectionUtil.java:31)
at io.netty.util.internal.PlatformDependent0$4.run(PlatformDependent0.java:225)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at io.netty.util.internal.PlatformDependent0.<clinit>(PlatformDependent0.java:219)
at io.netty.util.internal.PlatformDependent.isAndroid(PlatformDependent.java:273)
at io.netty.util.internal.PlatformDependent.<clinit>(PlatformDependent.java:92)
at io.netty.channel.epoll.Native.loadNativeLibrary(Native.java:225)
at io.netty.channel.epoll.Native.<clinit>(Native.java:57)
at io.netty.channel.epoll.Epoll.<clinit>(Epoll.java:39)
at io.ktor.server.netty.EventLoopGroupProxy$Companion.create(NettyApplicationEngine.kt:189)
at io.ktor.server.netty.NettyApplicationEngine.<init>(NettyApplicationEngine.kt:74)
at io.ktor.server.netty.EngineMain.main(EngineMain.kt:22)
19:21:11.814 [main] DEBUG io.netty.util.internal.PlatformDependent0 - java.nio.Bits.unaligned: available, true
19:21:11.815 [main] DEBUG io.netty.util.internal.PlatformDependent0 - jdk.internal.misc.Unsafe.allocateUninitializedArray(int): unavailable
java.lang.IllegalAccessException: class io.netty.util.internal.PlatformDependent0$6 cannot access class jdk.internal.misc.Unsafe (in module java.base) because module java.base does not export jdk.internal.misc to unnamed module @557caf28
at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:361)
at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:591)
at java.base/java.lang.reflect.Method.invoke(Method.java:558)
at io.netty.util.internal.PlatformDependent0$6.run(PlatformDependent0.java:335)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at io.netty.util.internal.PlatformDependent0.<clinit>(PlatformDependent0.java:326)
at io.netty.util.internal.PlatformDependent.isAndroid(PlatformDependent.java:273)
at io.netty.util.internal.PlatformDependent.<clinit>(PlatformDependent.java:92)
at io.netty.channel.epoll.Native.loadNativeLibrary(Native.java:225)
at io.netty.channel.epoll.Native.<clinit>(Native.java:57)
at io.netty.channel.epoll.Epoll.<clinit>(Epoll.java:39)
at io.ktor.server.netty.EventLoopGroupProxy$Companion.create(NettyApplicationEngine.kt:189)
at io.ktor.server.netty.NettyApplicationEngine.<init>(NettyApplicationEngine.kt:74)
at io.ktor.server.netty.EngineMain.main(EngineMain.kt:22)
</code></pre>
<p>the content of <strong>build.gradle.kts</strong> file </p>
<pre><code>plugins {
application
kotlin("jvm") version "1.3.61"
}
group = "io.flatmap"
version = "1.0-SNAPSHOT"
val ktor_version = "1.3.0"
repositories {
mavenCentral()
jcenter()
}
dependencies {
implementation(kotlin("stdlib-jdk8"))
compile("io.ktor:ktor-server-netty:$ktor_version")
compile("io.ktor:ktor-server-core:$ktor_version")
compile("ch.qos.logback:logback-classic:1.2.3")
testCompile(group = "junit", name = "junit", version = "4.12")
}
tasks {
compileKotlin {
kotlinOptions.jvmTarget = "11"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "11"
}
}
application {
mainClassName = "io.ktor.server.netty.EngineMain"
}
</code></pre>
<p>I am using Zulu OpenJDK 11: </p>
<pre><code> java --version
openjdk 11.0.6 2020-01-14 LTS
OpenJDK Runtime Environment Zulu11.37+17-CA (build 11.0.6+10-LTS)
OpenJDK 64-Bit Server VM Zulu11.37+17-CA (build 11.0.6+10-LTS, mixed mode)
</code></pre>
<p>What am I doing wrong? </p> | 60,241,952 | 1 | 5 | null | 2020-02-15 18:29:54.11 UTC | 3 | 2020-02-16 08:45:20.93 UTC | null | null | null | null | 1,743,843 | null | 1 | 22 | java|kotlin|netty|ktor | 38,019 | <p>The access level of each object member cannot be increased anymore. The operation is not allowed anymore since Java 9 and has been hardly disabled in release 11. </p>
<p>You need to run this application with Java 8.</p>
<p>See <a href="https://www.oracle.com/technetwork/java/javase/9-relnote-issues-3704069.html" rel="noreferrer">https://www.oracle.com/technetwork/java/javase/9-relnote-issues-3704069.html</a> (search for "setAccessible"). There is a new Object which must now be used to allow it again: <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/reflect/AccessibleObject.html" rel="noreferrer">https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/reflect/AccessibleObject.html</a></p> |
18,352,682 | Correct file permissions for WordPress | <p>I've had a look over <a href="https://wordpress.org/support/article/changing-file-permissions/" rel="noreferrer">here</a> but didn't find any details on the best file permissions. I also took a look at some of WordPress's form's questions over <a href="http://wordpress.org/support/topic/what-are-correct-file-permissions-1" rel="noreferrer">here too</a> but anybody that suggests 777 obviously needs a little lesson in security.</p>
<p>In short my question is this. What permissions should I have for the following:</p>
<ol>
<li>root folder storing all the WordPress content</li>
<li>wp-admin</li>
<li>wp-content</li>
<li>wp-includes</li>
</ol>
<p>and then all the files in each of those folders?</p> | 23,755,604 | 15 | 2 | null | 2013-08-21 08:39:57.667 UTC | 320 | 2020-01-24 23:38:56.33 UTC | 2019-06-17 19:38:11.177 UTC | null | 5,596,140 | null | 2,266,042 | null | 1 | 399 | php|wordpress|chmod | 799,264 | <p>When you setup WP you (the webserver) may need write access to the files. So the access rights may need to be loose.</p>
<pre class="lang-sh prettyprint-override"><code>chown www-data:www-data -R * # Let Apache be owner
find . -type d -exec chmod 755 {} \; # Change directory permissions rwxr-xr-x
find . -type f -exec chmod 644 {} \; # Change file permissions rw-r--r--
</code></pre>
<p><strong>After the setup you <em>should</em> tighten the access rights</strong>, according to <a href="https://wordpress.org/support/article/hardening-wordpress/" rel="noreferrer">Hardening WordPress</a> all files except for wp-content should be writable by your user account only. wp-content must be writable by <em>www-data</em> too.</p>
<pre class="lang-sh prettyprint-override"><code>chown <username>:<username> -R * # Let your useraccount be owner
chown www-data:www-data wp-content # Let apache be owner of wp-content
</code></pre>
<p>Maybe you want to change the contents in wp-content later on. In this case you could</p>
<ul>
<li>temporarily change to the user to <em>www-data</em> with <code>su</code>,</li>
<li>give wp-content group write access 775 and join the group <em>www-data</em> or </li>
<li>give your user the access rights to the folder using <a href="https://wiki.archlinux.org/index.php/Access_Control_Lists" rel="noreferrer">ACLs</a>.</li>
</ul>
<p>Whatever you do, make sure the files have rw permissions for <em>www-data</em>.</p> |
19,925,641 | Check if a Postgres JSON array contains a string | <p>I have a table to store information about my rabbits. It looks like this:</p>
<pre><code>create table rabbits (rabbit_id bigserial primary key, info json not null);
insert into rabbits (info) values
('{"name":"Henry", "food":["lettuce","carrots"]}'),
('{"name":"Herald","food":["carrots","zucchini"]}'),
('{"name":"Helen", "food":["lettuce","cheese"]}');
</code></pre>
<p>How should I find the rabbits who like carrots? I came up with this:</p>
<pre><code>select info->>'name' from rabbits where exists (
select 1 from json_array_elements(info->'food') as food
where food::text = '"carrots"'
);
</code></pre>
<p>I don't like that query. It's a mess.</p>
<p>As a full-time rabbit-keeper, I don't have time to change my database schema. I just want to properly feed my rabbits. Is there a more readable way to do that query?</p> | 27,144,175 | 7 | 2 | null | 2013-11-12 09:40:59.41 UTC | 44 | 2022-02-27 18:13:31.58 UTC | 2013-11-13 00:57:15.8 UTC | null | 1,115,979 | null | 1,115,979 | null | 1 | 209 | json|postgresql|postgresql-9.3 | 185,818 | <p>As of PostgreSQL 9.4, you can use the <a href="https://www.postgresql.org/docs/9.4/static/functions-json.html#FUNCTIONS-JSONB-OP-TABLE"><code>?</code> operator</a>:</p>
<pre><code>select info->>'name' from rabbits where (info->'food')::jsonb ? 'carrots';
</code></pre>
<p>You can even index the <code>?</code> query on the <code>"food"</code> key if you switch to the <em>jsonb</em> type instead:</p>
<pre><code>alter table rabbits alter info type jsonb using info::jsonb;
create index on rabbits using gin ((info->'food'));
select info->>'name' from rabbits where info->'food' ? 'carrots';
</code></pre>
<p>Of course, you probably don't have time for that as a full-time rabbit keeper.</p>
<p><strong>Update:</strong> Here's a demonstration of the performance improvements on a table of 1,000,000 rabbits where each rabbit likes two foods and 10% of them like carrots:</p>
<pre><code>d=# -- Postgres 9.3 solution
d=# explain analyze select info->>'name' from rabbits where exists (
d(# select 1 from json_array_elements(info->'food') as food
d(# where food::text = '"carrots"'
d(# );
Execution time: 3084.927 ms
d=# -- Postgres 9.4+ solution
d=# explain analyze select info->'name' from rabbits where (info->'food')::jsonb ? 'carrots';
Execution time: 1255.501 ms
d=# alter table rabbits alter info type jsonb using info::jsonb;
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
Execution time: 465.919 ms
d=# create index on rabbits using gin ((info->'food'));
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
Execution time: 256.478 ms
</code></pre> |
15,362,525 | when is onRestoreInstanceState called? | <p>Sorry for my incomprehension, but I am new in the android development.</p>
<p>I have an application with activity A and activity B in it, and I go from activity A to activity B. When I left activity A, the <code>onSaveInstanceState</code> method was called, but when I went back to activity A (from activity B in the same application), the bundle in the <code>onCreate</code> method was null.</p>
<p>What can I do, to save the activity A's previous state? I only want to store the data for the application lifetime.</p>
<p>Can someone help me with this?</p>
<p>Here is my code for Activity A:</p>
<pre><code>@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null)
{
Log.v("Main", savedInstanceState.getString("test"));
}
else
{
Log.v("Main", "old instance");
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
Log.v("Main", "save instance");
savedInstanceState.putString("test", "my test string");
super.onSaveInstanceState(savedInstanceState);
}
public void buttonClick(View view)
{
Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
}
</code></pre>
<p>Here is my code for Activity B, when I press a button to go back to activity A:</p>
<pre><code>public void onBack(View view)
{
NavUtils.navigateUpFromSameTask(this);
}
</code></pre> | 15,362,869 | 6 | 4 | null | 2013-03-12 13:25:02.077 UTC | 9 | 2022-02-17 12:10:46.93 UTC | 2018-04-24 15:09:01.75 UTC | user8389458 | null | null | 2,135,124 | null | 1 | 44 | android|android-lifecycle|onsaveinstancestate|onrestoreinstancestate | 41,432 | <p>Saving and restoring state is meant to save the current temporary data that is obsolete when user exits the application.
When you minimize or leave the Activity by opening next one it might be killed by the system due to lack of resources and restarted with <code>savedInstanceState</code> when you get back to it. So use <code>onSaveInstanceState()</code> only for saving minimize-restore session data or data that should be preserved on rotation.</p>
<p>So if you start a new Activity in front and get back to the previous one (what you are trying to do), the Activity A might not be killed (just stopped) and restarted without going being destroyed. You can force killing it and restoring by checking <code>Don't keep activities</code> in developer options menu.</p>
<p>If you call <code>finish()</code> or remove the <code>Activity</code> from recent task list the <code>savedInstanceState</code> will not be passed to <code>onCreate()</code> since the task was cleared.</p>
<p>If the value must be persistent consider using <code>SharedPreferences.</code></p> |
15,349,189 | MYSQL Left Join COUNTS from multiple tables | <p>I want to add columns that represent counts from other tables. </p>
<p>I have 3 tables. </p>
<p><strong>Messages</strong></p>
<pre><code>MessageID User Message Topic
1 Tom Hi ball
2 John Hey book
3 Mike Sup book
4 Mike Ok book
</code></pre>
<p><strong>Topics</strong></p>
<pre><code>Topic Title Category1 Category2
ball Sports Action Hot
book School Study Hot
</code></pre>
<p><strong>Stars_Given</strong></p>
<pre><code>starID Topic
1 ball
2 book
3 book
4 book
</code></pre>
<p>I want to end up with:</p>
<p><strong>Topic_Review</strong></p>
<pre><code>Topic Title StarCount UserCount MessageCount
ball Sports 1 1 1
book school 3 2 3
</code></pre>
<p>So basically I want to attach 3 columns with counts of unique values (number of stars given within each topic, unique users who have messages within topic, and the number of unique messages in each topic). </p>
<p>I want to eventually be able to filter on the categories (look in both columns) as well.</p>
<p>Also, I want to eventually sort by the counts that I join. Example, I'm going to have a button that sorts by "number of stars" by ascending order, or sort by "number of users" by descending order, etc. </p>
<p>I've tried adapting other people's answers and I can't get it to work properly.</p> | 15,349,249 | 1 | 0 | null | 2013-03-11 21:39:24.107 UTC | 22 | 2018-06-19 10:06:57.773 UTC | 2018-06-19 10:06:57.773 UTC | null | 759,866 | null | 1,998,113 | null | 1 | 44 | mysql|count|left-join | 64,986 | <pre><code>select
t.Topic,
t.Title,
count(distinct s.starID) as StarCount,
count(distinct m.User) as UserCount,
count(distinct m.messageID) as MessageCount
from
Topics t
left join Messages m ON m.Topic = t.Topic
left join Stars_Given s ON s.Topic = t.Topic
group by
t.Topic,
t.Title
</code></pre>
<h2><a href="http://sqlfiddle.com/#!2/3cf96/2">Sql Fiddle</a></h2>
<p>Or, you can perform the aggregation in sub-queries, which will likely be more efficient if you have a substantial amount of data in the tables:</p>
<pre><code>select
t.Topic,
t.Title,
s.StarCount,
m.UserCount,
m.MessageCount
from
Topics t
left join (
select
Topic,
count(distinct User) as UserCount,
count(*) as MessageCount
from Messages
group by Topic
) m ON m.Topic = t.Topic
left join (
select
Topic,
count(*) as StarCount
from Stars_Given
group by Topic
) s ON s.Topic = t.Topic
</code></pre>
<h2><a href="http://sqlfiddle.com/#!2/3cf96/5">Sql Fiddle</a></h2> |
15,439,841 | MVVM in WPF - How to alert ViewModel of changes in Model... or should I? | <p>I am going through some MVVM articles, primarily <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx">this</a> and <a href="http://rachel53461.wordpress.com/2011/05/08/simplemvvmexample/">this</a>.</p>
<p>My specific question is: <strong>How do I communicate Model changes from the Model to the ViewModel?</strong> </p>
<p>In Josh's article, I don't see that he does this. The ViewModel always asks the Model for properties. In Rachel's example, she does have the model implement <code>INotifyPropertyChanged</code>, and raises events from the model, but they are for consumption by the view itself (see her article/code for more detail on why she does this). </p>
<p>Nowhere do I see examples where the model alerts the ViewModel of changes to model properties. This has me worried that perhaps it's not done for some reason. <strong>Is there a pattern for alerting the ViewModel of changes in the Model?</strong> It would seem to be necessary as (1) conceivably there are more than 1 ViewModel for each model, and (2) even if there is just one ViewModel, some action on the model might result in other properties being changed. </p>
<p>I suspect that there might be answers/comments of the form "Why would you want to do that?" comments, so here's a description of my program. I'm new to MVVM so perhaps my whole design is faulty. I'll briefly describe it.</p>
<p>I am programming up something that is more interesting (at least, to me!) than "Customer" or "Product" classes. I am programming BlackJack. </p>
<p>I have a View that doesn't have any code behind and just relies on binding to properties and commands in the ViewModel (see Josh Smith's article). </p>
<p>For better or worse, I took the attitude that the Model should contain not just classes such as <code>PlayingCard</code>, <code>Deck</code>, but also the <code>BlackJackGame</code> class that keeps state of the whole game, and knows when the player has gone bust, the dealer has to draw cards, and what the player and dealer current score is (less than 21, 21, bust, etc.). </p>
<p>From <code>BlackJackGame</code> I expose methods like "DrawCard" and it occurred to me that when a card is drawn, properties such as <code>CardScore</code>, and <code>IsBust</code> should be updated and these new values communicated to the ViewModel. Perhaps that's faulty thinking? </p>
<p>One could take the attitude that the ViewModel called the <code>DrawCard()</code> method so he should know to ask for an updated score and find out if he is bust or not. Opinions? </p>
<p>In my ViewModel, I have the logic to grab an actual image of a playing card (based on suit,rank) and make it available for the view. The model should not be concerned with this (perhaps other ViewModel would just use numbers instead of playing card images). Of course, perhaps some will tell me that the Model should not even have the concept of a BlackJack game and that should be handled in the ViewModel?</p> | 15,440,949 | 11 | 5 | null | 2013-03-15 18:38:23.737 UTC | 55 | 2017-04-04 14:15:17.143 UTC | 2015-12-27 18:39:19.973 UTC | null | 809,009 | null | 286,641 | null | 1 | 127 | c#|.net|wpf|mvvm | 110,726 | <p>If you want your Models to alert the ViewModels of changes, they should implement <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx">INotifyPropertyChanged</a>, and the ViewModels should subscribe to receive PropertyChange notifications.</p>
<p>Your code might look something like this:</p>
<pre><code>// Attach EventHandler
PlayerModel.PropertyChanged += PlayerModel_PropertyChanged;
...
// When property gets changed in the Model, raise the PropertyChanged
// event of the ViewModel copy of the property
PlayerModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "SomeProperty")
RaisePropertyChanged("ViewModelCopyOfSomeProperty");
}
</code></pre>
<p>But typically this is only needed if more than one object will be making changes to the Model's data, which is not usually the case.</p>
<p>If you ever have a case where you don't actually have a reference to your Model property to attach the PropertyChanged event to it, then you can use a Messaging system such as Prism's <code>EventAggregator</code> or MVVM Light's <code>Messenger</code>.</p>
<p>I have a <a href="http://rachel53461.wordpress.com/2011/06/05/communication-between-viewmodels-with-mvvm/">brief overview of messaging systems</a> on my blog, however to summarize it, any object can broadcast a message, and any object can subscribe to listen for specific messages. So you might broadcast a <code>PlayerScoreHasChangedMessage</code> from one object, and another object can subscribe to listen for those types of messages and update it's <code>PlayerScore</code> property when it hears one.</p>
<p>But I don't think this is needed for the system you have described.</p>
<p>In an ideal MVVM world, your application is comprised of your ViewModels, and your Models are the just the blocks used to build your application. They typically only contain data, so would not have methods such as <code>DrawCard()</code> (that would be in a ViewModel)</p>
<p>So you would probably have plain Model data objects like these:</p>
<pre><code>class CardModel
{
int Score;
SuitEnum Suit;
CardEnum CardValue;
}
class PlayerModel
{
ObservableCollection<Card> FaceUpCards;
ObservableCollection<Card> FaceDownCards;
int CurrentScore;
bool IsBust
{
get
{
return Score > 21;
}
}
}
</code></pre>
<p>and you'd have a ViewModel object like</p>
<pre><code>public class GameViewModel
{
ObservableCollection<CardModel> Deck;
PlayerModel Dealer;
PlayerModel Player;
ICommand DrawCardCommand;
void DrawCard(Player currentPlayer)
{
var nextCard = Deck.First();
currentPlayer.FaceUpCards.Add(nextCard);
if (currentPlayer.IsBust)
// Process next player turn
Deck.Remove(nextCard);
}
}
</code></pre>
<p>(Above objects should all implement <code>INotifyPropertyChanged</code>, but I left it out for simplicity)</p> |
28,325,813 | SqlDataReader Get Value By Column Name (Not Ordinal Number) | <p>Using the <a href="https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader_methods%28v=vs.110%29.aspx" rel="noreferrer">methods of the SqlDataReader</a>, I can get the value of a column by passing in it's ordinal, such as the value of the first column if I pass in <code>read.GetValue(0)</code>, or the second column if I pass in <code>read.GetValue(1)</code>. </p>
<p>In looking at the methods, I don't see an option to get the value of a column by passing in the name of a column, such as ColumnID. In my mythical example, I would want to pass in <code>read.GetValueofColumn("ColumnID")</code> and read the value in the column (<strong>note that the method <code>GetValueofColumn</code> doesn't exist so far as I can tell from the method list</strong>).</p>
<p>Am I missing the method to do this, or a way to do this?</p> | 28,325,878 | 5 | 3 | null | 2015-02-04 15:59:41.467 UTC | 9 | 2020-10-13 07:27:39.107 UTC | 2017-03-19 21:59:18.657 UTC | null | 13,302 | null | 3,807,672 | null | 1 | 42 | c#|sqldatareader | 80,200 | <p>You can get the ordinal of the column by using the <code>GetOrdinal</code> method, so your call could be:</p>
<pre><code>read.GetValue(read.GetOrdinal("ColumnID"));
</code></pre> |
7,729,301 | How to ForwardAgent yes using fabric? | <p>I am successfully <code>run()</code>ning commands on remote server with my private key pair.</p>
<p>However, I'd like to do <code>git clone ssh://private/repo</code> on remote server using my local key (or using local ssh agent I'm in).</p>
<p>How to do it using fabric?</p> | 10,211,889 | 2 | 3 | null | 2011-10-11 16:24:18.89 UTC | 11 | 2012-05-08 12:04:46.963 UTC | null | null | null | null | 123,558 | null | 1 | 31 | python|deployment|automation|fabric | 8,502 | <p>Since version 1.4 <code>fabric</code> has <a href="http://docs.fabfile.org/en/1.4.1/usage/env.html?highlight=forwarding#forward-agent" rel="noreferrer">environment option</a> that enables agent forwarding.</p>
<pre><code>env.forward_agent = True
</code></pre>
<p><strong>UPD</strong>: This feature <a href="https://github.com/fabric/fabric/issues/562" rel="noreferrer">was buggy</a> before <code>fabric</code> 1.4.2</p> |
8,300,185 | Combining :last-child with :not(.class) selector in CSS | <p>Is it possible to choose the last child that does NOT have a class attr?
Like such:</p>
<pre><code><tr> ... </tr>
<tr> ... </tr>
<tr> ... </tr>
<tr class="table_vert_controls"> ... </tr>
</code></pre>
<p>I want to select the third row, in this case.</p>
<p>I tried the following, which did not work:</p>
<pre><code>tr:not(.table_vert_controls):last-child
</code></pre>
<p>Thanks in advance.</p> | 8,300,258 | 2 | 4 | null | 2011-11-28 18:01:39.657 UTC | 3 | 2018-08-18 21:05:05.487 UTC | 2011-11-28 18:06:18.083 UTC | null | 106,224 | null | 857,807 | null | 1 | 44 | css|css-selectors | 29,874 | <p>Not with CSS selectors alone, no, as <code>:last-child</code> specifically looks at <em>the last child</em>, and there isn't a similar <code>:last-of-class</code> pseudo-class. See my answer to <a href="https://stackoverflow.com/questions/5545649/can-i-combine-nth-child-or-nth-of-type-with-an-arbitrary-selector/5546296#5546296">this related question</a>.</p>
<p>As of late 2015, implementations have begun slowly trickling in for Selectors 4's extension to <code>:nth-child()</code> and <code>:nth-last-child()</code> which allow you to pass an arbitrary selector as an argument (more on that also in an update to the linked answer). You will then be able to write the following:</p>
<pre><code>tr:nth-last-child(1 of :not(.table_vert_controls))
</code></pre>
<p>Although implementations have recently begun to ship, it will still take at least a few more years for this to be widely supported (as of April 2018, two and a half years after being the first browser to ship, <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child#Browser_compatibility" rel="noreferrer">Safari remains the only browser to have done so</a>). In the meantime, you'll have to use something else, like an extra class just before the class in question, or a jQuery selector:</p>
<pre><code>$('tr:not(.table_vert_controls):last')
</code></pre> |
8,620,127 | Maven in Eclipse: step by step installation | <p>I have spent been on the Maven site reading the 5- and 30-minute tutorials, and trialing Maven out for the first time.</p>
<p>I want to install a Maven plugin and use it to start building Maven projects from Eclipse.</p>
<p>Despite an honest effort, I have been unable to find a comprehensive tutorial on any Maven plugin. <code>M2E</code>, which seems like the de facto standard, has nothing but broken (or recursive) links on their site.</p>
<p>I can't tell if I even installed the plugin correctly, or how to use it.</p>
<p>Does anyone know of a good step-by-step guide to <code>M2E</code> or any other plugin? One that comes with good installation documentation, along with a solid explanation of its features and proper uses?</p> | 13,640,110 | 13 | 3 | null | 2011-12-23 19:59:21.7 UTC | 120 | 2020-01-10 11:07:50.66 UTC | 2017-04-05 15:07:46.493 UTC | null | 2,756,409 | null | 892,029 | null | 1 | 347 | eclipse|maven|eclipse-plugin | 1,004,708 | <p>(Edit 2016-10-12: Many Eclipse downloads from <a href="https://eclipse.org/downloads/eclipse-packages/" rel="noreferrer">https://eclipse.org/downloads/eclipse-packages/</a> have M2Eclipse included already. As of Neon both the Java and the Java EE packages do - look for "Maven support")</p>
<p><strong>Way 1:</strong> Maven Eclipse plugin installation step by step:</p>
<ol>
<li>Open Eclipse IDE</li>
<li>Click Help -> Install New Software...</li>
<li>Click Add button at top right corner</li>
<li><p>At pop up: fill up Name as "M2Eclipse" and Location as "<a href="http://download.eclipse.org/technology/m2e/releases" rel="noreferrer">http://download.eclipse.org/technology/m2e/releases</a>"
or
<a href="http://download.eclipse.org/technology/m2e/milestones/1.0" rel="noreferrer">http://download.eclipse.org/technology/m2e/milestones/1.0</a></p></li>
<li><p>Now click OK</p></li>
</ol>
<p>After that installation would be started.</p>
<p><strong>Way 2:</strong> Another way to install Maven plug-in for Eclipse by "Eclipse Marketplace":</p>
<ol>
<li>Open Eclipse</li>
<li>Go to Help -> Eclipse Marketplace</li>
<li>Search by Maven</li>
<li>Click "Install" button at "Maven Integration for Eclipse" section</li>
<li>Follow the instruction step by step</li>
</ol>
<p>After successful installation do the followings in Eclipse:</p>
<ol>
<li>Go to Window --> Preferences<br></li>
<li>Observe, Maven is enlisted at left panel</li>
</ol>
<p>Finally,</p>
<ol>
<li>Click on an existing project</li>
<li>Select Configure -> Convert to Maven Project</li>
</ol> |
8,723,545 | WCF Client - 407 Proxy Authentication Required while running webservice | <p>I've created simple WinForms app that uses free webservice <a href="http://www.webservicemart.com/uszip.asmx" rel="noreferrer"><b><a href="http://www.webservicemart.com/uszip.asmx" rel="noreferrer">http://www.webservicemart.com/uszip.asmx</a></b></a>. But this app fails to use service operation with error:</p>
<blockquote>
<p>The remote server returned an unexpected response: (407) Proxy Authentication Required (The ISA Server requires authorization to fulfill the request. Access to the Web Proxy service is denied)</p>
</blockquote>
<p>Code that creates proxy and triggers service operation:</p>
<pre><code>ChannelFactory<ServiceReference1.USZipSoap> proxy = new ChannelFactory<ServiceReference1.USZipSoap>("USZipSoap");
ServiceReference1.USZipSoap client = proxy.CreateChannel();
string str = client.ValidateZip("12345");
MessageBox.Show(str);
</code></pre>
<p>Is this problem with a network of my company or this is a proxy on the side of <a href="http://www.webservicemart.com" rel="noreferrer"><b>webservicemart.com</b></a>?</p>
<p>I've googled a lot of information on changing configuration files, creating a custom binding, etc. But I feel the lack of more basic understanding...<br> If this error is about ISA server of our corporate network then what configuration should I make to ISA Server to not restrict me from using external webservices?</p> | 8,727,924 | 5 | 4 | null | 2012-01-04 07:42:50.007 UTC | 6 | 2017-09-19 22:53:44.66 UTC | 2013-05-07 11:13:40.813 UTC | null | 13,302 | null | 982,424 | null | 1 | 15 | wcf|web-services|proxy|isaserver|http-status-code-407 | 46,230 | <p>In your binding configuration make sure that <code>useDefaultWebProxy</code> is set to true - it will use configuration you have found in IE. In your configuration file add following snippet to ensure default your credentials are used for authentication on the proxy server: </p>
<pre><code><system.net>
<defaultProxy useDefaultCredentials="true" />
</system.net>
</code></pre> |
5,385,234 | Using sed/awk to print lines with matching pattern OR another matching pattern | <p>I need to print lines in a file matching a pattern <em>OR</em> a different pattern using <a href="/questions/tagged/awk" class="post-tag" title="show questions tagged 'awk'" rel="tag">awk</a> or <a href="/questions/tagged/sed" class="post-tag" title="show questions tagged 'sed'" rel="tag">sed</a>. I feel like this is an easy task but I can't seem to find an answer. Any ideas?</p> | 5,385,259 | 4 | 0 | null | 2011-03-22 00:10:49.76 UTC | 6 | 2013-08-13 19:58:35.123 UTC | 2013-08-13 19:58:35.123 UTC | null | 1,275,165 | null | 609,330 | null | 1 | 30 | bash|sed|awk | 95,923 | <p>The POSIX way</p>
<pre><code>awk '/pattern1/ || /pattern2/{print}'
</code></pre>
<h3>Edit</h3>
<p>To be fair, I like <em>lhf</em>'s way better via <code>/pattern1|pattern2/</code> since it requires less typing for the same outcome. However, I should point out that this template cannot be used for <strong>logical AND</strong> operations, for that you need to use my template which is <code>/pattern1/ && /pattern2/</code></p> |
4,956,209 | problem in ant build invalid target release | <p>problem in ant build </p>
<pre><code>[javac] Compiling 86 source files to F:\XXX\classes
[javac] javac: invalid target release: 1.6
[javac] Usage: javac <options> <source files>
[javac] where possible options include:
[javac] -g Generate all debugging info
[javac] -g:none Generate no debugging info
[javac] -g:{lines,vars,source} Generate only some debugging info
[javac] -nowarn Generate no warnings
[javac] -verbose Output messages about what the compiler is doing
[javac] -deprecation Output source locations where deprecated APIs are used
[javac] -classpath <path> Specify where to find user class files
[javac] -cp <path> Specify where to find user class files
[javac] -sourcepath <path> Specify where to find input source files
[javac] -bootclasspath <path> Override location of bootstrap class files
[javac] -extdirs <dirs> Override location of installed extensions
[javac] -endorseddirs <dirs> Override location of endorsed standards path
[javac] -d <directory> Specify where to place generated class files
[javac] -encoding <encoding> Specify character encoding used by source files
[javac] -source <release> Provide source compatibility with specified release
[javac] -target <release> Generate class files for specific VM version
[javac] -version Version information
[javac] -help Print a synopsis of standard options
[javac] -X Print a synopsis of nonstandard options
[javac] -J<flag> Pass <flag> directly to the runtime system
BUILD FAILED
</code></pre>
<p>ant source and target to 1.6
en variable path to jdk 1.6</p> | 4,956,260 | 5 | 1 | null | 2011-02-10 10:59:36.913 UTC | null | 2014-05-22 16:45:37.92 UTC | 2011-02-10 11:00:53.983 UTC | null | 21,005 | null | 555,843 | null | 1 | 17 | java|ant | 43,892 | <p>You use a compiler that cannot compile with <code>-target 1.6</code> (javac: invalid target release: 1.6). Are you sure you use the JDK 1.6? Maybe a JDK 1.5 is installed and used by ant. Check the used Java-version with adding following line to your target (at the beginning):</p>
<pre><code><echo message="Using Java version ${ant.java.version}."/>
</code></pre>
<p>It outputs the Java-version used by Ant.</p>
<p>You can set the compiler to use a different Java-version. You have to use the fork-attribute to use an external javac and specify which one you want:</p>
<pre><code><javac srcdir="${src}"
destdir="${build}"
fork="yes"
executable="/opt/java/jdk1.6/bin/javac"
/>
</code></pre>
<p>Read the documentation of the <a href="http://ant.apache.org/manual/Tasks/javac.html" rel="noreferrer">javac-task</a> for details.</p> |
4,978,567 | Should a return statement have parentheses? | <p>Suppose we have in Python 3.x (and I guess in Python 2.6 and in Python 2.7 too) the following functions:</p>
<pre><code>>>> def dbl_a(p): return p*2
>>> def dbl_b(p): return(p*2)
>>> def dbl_c(p): return (p*2)
</code></pre>
<p>If we run them we get:</p>
<pre><code>>>> dbl_a(42)
84
>>> dbl_b(42)
84
>>> dbl_c(42)
84
</code></pre>
<p>The three functions provide the same result (value and type) and they seem to be equivalent. </p>
<p>But which of them has the more correct <code>return</code> statement?</p>
<p>Is there any side-effect in any of those definitions?</p>
<p>The same questions apply to the following situation with multiple values returned:</p>
<pre><code>>>> def dbl_triple_a(p): return p*2, p*3
>>> def dbl_triple_b(p): return(p*2, p*3)
>>> def dbl_triple_c(p): return (p*2, p*3)
>>> dbl_triple_a(42)
(84, 126)
>>> dbl_triple_b(42)
(84, 126)
>>> dbl_triple_c(42)
(84, 126)
</code></pre>
<p>In this case every function returns a <strong>tuple</strong>, but my questions still remain the same.</p> | 4,979,486 | 5 | 0 | null | 2011-02-12 14:24:47.26 UTC | 11 | 2017-10-08 18:22:32.34 UTC | 2012-10-05 00:57:53.623 UTC | null | 307,705 | null | 605,209 | null | 1 | 54 | python | 28,771 | <p>There are generally 4 uses for the parentheses <code>()</code> in Python.</p>
<ol>
<li>It acts the same way as most of the other mainstream languages - it's a construct to force an evaluation precedence, like in a math formula. Which also means it's only used when it is necessary, like when you need to make sure additions and subtractions happen first before multiplications and divisions.</li>
<li><s>It is a construct to group immutable values together in the same spirit as a similar set notation in math. We call this a tuple in Python. Tuple is also a basic type.</s> It is a construct to make an empty tuple and force operator precedence elevation.</li>
<li>It is used to group imported names together in import statements so you don't have to use the multi-line delimiter <code>\</code>. This is mostly stylistic.</li>
<li>In long statements like</li>
</ol>
<pre>
<code>
decision = (is_female and under_30 and single
or
is_male and above_35 and single)
</code>
</pre>
<p>the parenthesis is an alternative syntax to avoid hitting the 80 column limit and having to use <code>\</code> for statement continuation.</p>
<p>In any other cases, such as inside the <code>if</code>, <code>while</code>, <code>for</code> predicates and the <code>return</code> statement I'd strongly recommend not using <code>()</code> unless necessary or aid readability (defined by the 4 points above). One way to get this point across is that in math, <code>(1)</code> and just <code>1</code> means exactly the same thing. The same holds true in Python.</p>
<p>People coming from the C-family of languages will take a little bit getting used to this because the <code>()</code> are required in control-flow predicates in those languages for historical reasons.</p>
<p>Last word for <code>return</code> statements, if you are only returning 1 value, omit the <code>()</code>. But if you are returning multiple values, it's OK to use <code>()</code> because now you are returning a grouping, and the <code>()</code> enforces that visually. This last point is however stylistic and subject to preference. Remember that the <code>return</code> keywords returns the result of a <strong>statement</strong>. So if you only use <code>,</code> in your multiple assignment statements and tuple constructions, omit the <code>()</code>, but if you use <code>()</code> for value unpacking and tuple constructions, use <code>()</code> when you are returning multiple values in <code>return</code>. Keep it consistent.</p> |
5,012,525 | Get Root/Base Url In Spring MVC | <p>What is the best way to get the root/base url of a web application in Spring MVC? </p>
<p>Base Url = <a href="http://www.example.com">http://www.example.com</a> or <a href="http://www.example.com/VirtualDirectory">http://www.example.com/VirtualDirectory</a></p> | 15,718,815 | 13 | 3 | null | 2011-02-16 04:25:39.277 UTC | 15 | 2021-11-09 01:21:14.477 UTC | 2014-05-12 15:19:09.013 UTC | null | 100,297 | null | 280,602 | null | 1 | 49 | spring-mvc|base-url | 127,184 | <p>If base url is "<a href="http://www.example.com">http://www.example.com</a>", then use the following to get the "<em>www.example.com</em>" part, without the "http://":</p>
<p><strong>From a Controller:</strong></p>
<pre><code>@RequestMapping(value = "/someURL", method = RequestMethod.GET)
public ModelAndView doSomething(HttpServletRequest request) throws IOException{
//Try this:
request.getLocalName();
// or this
request.getLocalAddr();
}
</code></pre>
<p><strong>From JSP:</strong></p>
<p>Declare this on top of your document:</p>
<pre><code><c:set var="baseURL" value="${pageContext.request.localName}"/> //or ".localAddr"
</code></pre>
<p>Then, to use it, reference the variable:</p>
<pre><code><a href="http://${baseURL}">Go Home</a>
</code></pre> |
4,973,095 | How to change the type of a field? | <p>I am trying to change the type of a field from within the mongo shell.</p>
<p>I am doing this...</p>
<pre><code>db.meta.update(
{'fields.properties.default': { $type : 1 }},
{'fields.properties.default': { $type : 2 }}
)
</code></pre>
<p>But it's not working!</p> | 4,973,632 | 13 | 1 | null | 2011-02-11 19:18:37.263 UTC | 92 | 2022-09-16 16:37:44.037 UTC | 2019-06-12 20:43:54.113 UTC | null | 9,297,144 | null | 574,676 | null | 1 | 192 | mongodb | 250,377 | <p>The only way to change the <code>$type</code> of the data is to perform an update on the data where the data has the correct type.</p>
<p>In this case, it looks like you're trying to change the <code>$type</code> <a href="https://web.archive.org/web/20120505000412/http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24type" rel="noreferrer">from 1 (double) to 2 (string)</a>.</p>
<p>So simply load the document from the DB, perform the cast (<code>new String(x)</code>) and then save the document again.</p>
<p>If you need to do this programmatically and entirely from the shell, you can use the <code>find(...).forEach(function(x) {})</code> syntax.</p>
<hr>
<p>In response to the second comment below. Change the field <code>bad</code> from a number to a string in collection <code>foo</code>.</p>
<pre><code>db.foo.find( { 'bad' : { $type : 1 } } ).forEach( function (x) {
x.bad = new String(x.bad); // convert field to string
db.foo.save(x);
});
</code></pre> |
16,781,064 | Three.js multiple materials on object loaded via OBJMTLLoader | <p>I have ".obj" and ".mtl" files of a model and I'm loading it via <code>OBJMTLLoader</code>. ".mtl" specifies texture to apply to a model, and three.js loads model and renders it with applied texture just fine.</p>
<p>But here's the thing.</p>
<p>Once an object is loaded, I would like to apply another texture onto it. This is because first texture represents surface material of an object. And second texture is a drawing, that I'd like to position at a specific location on a model.</p>
<p>My question is: <strong>how to apply a second texture onto already loaded (and texturized) object</strong>?</p>
<p>I see that three.js creates an instance of <code>THREE.Object3D</code>, and that instance has "children" array with one instance of <code>THREE.Mesh</code>.</p>
<p>When I try to apply a texture to that mesh (<code>mesh.material.map = texture</code>), I lose initial texture.</p>
<p>I looked into this <a href="https://stackoverflow.com/questions/14932329/multiple-materials-with-jsonloader">question about applying multiple textures and JSONLoader</a> but didn't find an answer.</p>
<p>I also tried using <code>new THREE.MeshFaceMaterial( materials )</code> (as suggested in <a href="https://stackoverflow.com/a/12439857/130652">this answer</a>) but unsuccessfully.</p>
<p><strong>UPDATE</strong>:</p>
<p>I tried @WestLangley's suggestion to use multi-material object, but am still unable to render one material on top of another one.</p>
<p>I made this simple demo, adapted from three.js OBJLoader — <a href="http://dl.dropboxusercontent.com/u/822184/webgl_multiple_texture/index.html" rel="nofollow noreferrer">http://dl.dropboxusercontent.com/u/822184/webgl_multiple_texture/index.html</a></p>
<p>I'm using <code>THREE.SceneUtils.createMultiMaterialObject</code> as suggested, passing it cloned geometry of main mesh loaded from .obj. I'm also giving it 2 textures — one for entire surface, another one — for front surface of the model.</p>
<p>But this doesn't work. I added 2 checkboxes that toggle "visible" property of corresponding materials. You can see that materials are present, but I can't see the first one from beneath second one.</p>
<p>The crux of the loading/rendering is as follows:</p>
<pre><code>var texture = THREE.ImageUtils.loadTexture('fabric.jpg');
var texture2 = THREE.ImageUtils.loadTexture('table.jpg');
texture2.offset.set(-0.65, -2.5);
texture2.repeat.set(4, 4);
var loader = new THREE.OBJLoader();
loader.addEventListener( 'load', function ( event ) {
var mainMesh = event.content.children[0].children[0];
multiMaterialObject = THREE.SceneUtils.createMultiMaterialObject(
mainMesh.geometry.clone(), [
new THREE.MeshLambertMaterial({ map: texture2 }),
new THREE.MeshLambertMaterial({ map: texture })
]);
multiMaterialObject.position.y = -80;
scene.add(multiMaterialObject);
});
loader.load( 'male02.obj' );
</code></pre>
<p><strong>UPDATE #2</strong></p>
<p>At this point, I think the best bet is to use <code>THREE.ShaderMaterial</code> to apply one texture onto another. I see some <a href="https://stackoverflow.com/questions/12627422/custom-texture-shader-in-three-js">examples of using one texture</a> but still unsure how to display both in overlaid state. I'm also not sure how to position texture at a specific location on a mesh.</p> | 16,781,472 | 2 | 2 | null | 2013-05-27 22:00:25.307 UTC | 11 | 2018-05-12 01:01:46.67 UTC | 2018-05-12 01:01:46.67 UTC | null | 128,511 | null | 130,652 | null | 1 | 8 | javascript|three.js|textures|mesh | 24,775 | <p>You have several choices:</p>
<ol>
<li><p>You can mix the images on the javascript side using canvas tools, and create a single material with a single texture map.</p></li>
<li><p>You can create a multi-material object from a single geometry and an array of materials. (This approach just creates multiple identical meshes, each with one of the materials, and usually is used when one of the materials is wireframe. It may also work OK if one material is transparent.)</p>
<p><code>THREE.SceneUtils.createMultiMaterialObject( geometry, materials );</code></p></li>
<li><p>You can achieve a multi-texture effect with a custom <code>ShaderMaterial</code>. Have two texture inputs, and implement color mixing in the shader.</p></li>
</ol>
<p>Here an example of just about the simplest three.js <code>ShaderMaterial</code> possible that implements mixing of two textures: <a href="https://jsfiddle.net/6bg4qdhx/3/" rel="nofollow noreferrer">https://jsfiddle.net/6bg4qdhx/3/</a>.</p>
<hr>
<p>EDIT: Also see <a href="https://stackoverflow.com/questions/49702885/is-there-a-built-in-way-to-layer-textures-within-the-standard-pbr-shader/49708915#49708915">Is there a built-in way to layer textures within the standard PBR shader?</a></p>
<p>three.js r.92</p> |
41,365,446 | How to resolve "ImportError: DLL load failed:" on Python? | <p>Recently I start to get <code>ImportError: DLL load failed:</code> error when I import different libraries (for example <code>scikit-learn</code> or <code>scipy</code> and some others).</p>
<p>My assumptions is that I have broken something when I was trying to pip install opencv.</p>
<p>So, my question is how to resolve this problem that seems to be not library specific?</p>
<p>Can I pip install DLL or something like that? Can I just reinstall the whole Python? I am working on Windows. My version of Python is <code>Python 2.7.10 :: Anaconda 2.3.0 (64-bit)</code>.</p>
<p><strong>ADDED</strong></p>
<p>If I print <code>sys.path</code> I get this:</p>
<pre><code>['',
'C:\\Anaconda\\Scripts',
'C:\\Anaconda\\python27.zip',
'C:\\Anaconda\\DLLs',
'C:\\Anaconda\\lib',
'C:\\Anaconda\\lib\\plat-win',
'C:\\Anaconda\\lib\\lib-tk',
'C:\\Anaconda',
'C:\\Anaconda\\lib\\site-packages',
'C:\\Anaconda\\lib\\site-packages\\Sphinx-1.3.1-py2.7.egg',
'C:\\Anaconda\\lib\\site-packages\\cryptography-0.9.1-py2.7-win-amd64.egg',
'C:\\Panda3D-1.9.2-x64',
'C:\\Panda3D-1.9.2-x64\\bin',
'C:\\Anaconda\\lib\\site-packages\\win32',
'C:\\Anaconda\\lib\\site-packages\\win32\\lib',
'C:\\Anaconda\\lib\\site-packages\\Pythonwin',
'C:\\Anaconda\\lib\\site-packages\\setuptools-17.1.1-py2.7.egg',
'C:\\Anaconda\\lib\\site-packages\\IPython\\extensions',
'C:\\Users\\myname\\.ipython']
</code></pre>
<p>What worries me is that there is a mixture of 32 and 64 versions. Another thing, maybe I just have different Pythons and I just need to call the proper one?</p> | 41,376,679 | 7 | 3 | null | 2016-12-28 15:51:42.607 UTC | 4 | 2022-09-09 19:25:41.357 UTC | 2016-12-28 16:08:06.313 UTC | null | 245,549 | null | 245,549 | null | 1 | 15 | python|pip|importerror|ddl | 62,008 | <p>I have managed to resolve the problem by reinstalling Python. First, I have uninstalled Python (like any other program in Windows). Then I have installed Anaconda distribution of Python. The problem is not present anymore.</p> |
41,274,007 | Anaconda export Environment file | <p>How can I make anaconda environment file which could be use on other computers?</p>
<p>I exported my anaconda python environment to YML using <code>conda env export > environment.yml</code>. The exported <code>environment.yml</code> contains this line <code>prefix: /home/superdev/miniconda3/envs/juicyenv</code> which maps to my anaconda's location which will be different on other's pcs.</p> | 41,274,348 | 8 | 3 | null | 2016-12-22 00:19:52.343 UTC | 84 | 2022-07-28 13:49:55.753 UTC | null | null | null | null | 6,304,774 | null | 1 | 229 | python|python-3.x|anaconda|conda | 236,996 | <p>I can't find anything in the <code>conda</code> specs which allows you to export an environment file without the <code>prefix: ...</code> line. However, like <a href="https://stackoverflow.com/questions/41274007/anaconda-export-environment-file/41274348#comment69750196_41274007">Alex pointed out</a> in the comments, conda doesn't seem to care about the prefix line when creating an environment from the file.</p>
<p>With that in mind, if you want the other user to have no knowledge of your default install path, you can remove the prefix line with <code>grep</code> before writing to <code>environment.yml</code>.</p>
<pre><code>conda env export | grep -v "^prefix: " > environment.yml
</code></pre>
<p>Either way, the other user then runs:</p>
<pre><code>conda env create -f environment.yml
</code></pre>
<p>and the environment will get installed in their default conda environment path.</p>
<p>If you want to specify a different install path than the default for your system (not related to 'prefix' in the environment.yml), just use the <code>-p</code> flag followed by the required path.</p>
<pre><code>conda env create -f environment.yml -p /home/user/anaconda3/envs/env_name
</code></pre>
<p>Note that Conda recommends creating the <code>environment.yml</code> by hand, which is especially important if you are wanting to share your environment across platforms (Windows/Linux/Mac). In this case, you can just leave out the <code>prefix</code> line.</p> |
12,219,058 | How to debug a Chrome browser extension which is crashing? | <p>I have developed a Chrome browser extension and, on rare occasion, it crashes (eg, a bubble appears in the upper-right stating "_____ has crashed! Click here to reload it.")</p>
<p>The problem is that when it does so, background.html disappears (dies) immediately, and I cannot find any information to help me debug what went wrong. I've opened chrome://crashes and see that there are entries there which might correspond to my issue, but the crash log only gives me a link to file a bug report (no ability to download or view the log).</p>
<p>Based upon <a href="http://support.google.com/chrome/bin/answer.py?hl=en&answer=107788" rel="noreferrer">this Goole entry on finding crash</a> logs I've found some .dmp files, but they are essentially unreadable (the .dmp files seem to be some sort of un-symbolicated stack trace, or something of that nature).</p>
<p>Does anybody have a good way to debug Chrome extension crashes?</p>
<hr>
<p>EDIT: after further investigation, I have determined that chrome://crashes do not relate to my extension crashes. I just had a crash, yet the latest timestamp in chrome://crashes is from several hours ago.</p> | 12,233,986 | 1 | 4 | null | 2012-08-31 16:12:29.637 UTC | 7 | 2013-09-14 18:39:07.617 UTC | 2012-08-31 16:29:59.603 UTC | null | 559,301 | null | 559,301 | null | 1 | 28 | google-chrome|google-chrome-extension | 9,960 | <p><a href="http://geek.michaelgrace.org/2012/08/advanced-google-chrome-logging/" rel="noreferrer">I once had a similar issue</a> and was able to figure out the root of the issue by starting chrome with verbose logging enabled. To start Google Chrome on Mac with verbose logging you'll need to open a terminal and run something similar to the following:</p>
<pre><code>/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --enable-logging --v=1&
</code></pre>
<p>Then watch the debug log file by tailing the log file.</p>
<pre><code>tail -f ~/Library/Application\ Support/Google/Chrome/chrome_debug.log
</code></pre>
<p>On Ubuntu try:</p>
<pre><code>tail -f ~/.config/google-chrome/chrome_debug.log
</code></pre>
<p>It's very chatty but it may be just enough to help you fix your issue. </p>
<p><img src="https://i.stack.imgur.com/84FCa.jpg" alt="enter image description here"></p> |
12,248,703 | Creating an instance of class | <p>What's the difference between lines 1 , 2 , 3 , 4?</p>
<p>When do I use each?</p>
<p>Why line 3 prints the <code>constructor Foo</code> and line 7 returns an error and line 8 doesn't?</p>
<pre><code>#include <iostream>
using namespace std;
class Foo
{
public:
Foo ( )
{
cout << "constructor Foo\n";
}
};
class Bar
{
public:
Bar ( Foo )
{
cout << "constructor Bar\n";
}
};
int main()
{
/* 1 */ Foo* foo1 = new Foo ();
/* 2 */ Foo* foo2 = new Foo;
/* 3 */ Foo foo3;
/* 4 */ Foo foo4 = Foo::Foo();
/* 5 */ Bar* bar1 = new Bar ( *new Foo() );
/* 6 */ Bar* bar2 = new Bar ( *new Foo );
/* 7 */ Bar* bar3 = new Bar ( Foo foo5 );
/* 8 */ Bar* bar3 = new Bar ( Foo::Foo() );
return 1;
}
</code></pre> | 12,248,783 | 3 | 6 | null | 2012-09-03 13:18:57.07 UTC | 69 | 2012-09-03 16:56:29.957 UTC | 2012-09-03 13:29:45.247 UTC | null | 673,730 | null | 1,574,294 | null | 1 | 127 | c++|class|constructor | 265,968 | <pre><code> /* 1 */ Foo* foo1 = new Foo ();
</code></pre>
<p>Creates an object of type <code>Foo</code> in dynamic memory. <code>foo1</code> points to it. Normally, you wouldn't use raw pointers in C++, but rather a smart pointer. If <code>Foo</code> was a POD-type, this would perform value-initialization (it doesn't apply here).</p>
<pre><code> /* 2 */ Foo* foo2 = new Foo;
</code></pre>
<p>Identical to before, because <code>Foo</code> is not a POD type.</p>
<pre><code> /* 3 */ Foo foo3;
</code></pre>
<p>Creates a <code>Foo</code> object called <code>foo3</code> in automatic storage.</p>
<pre><code> /* 4 */ Foo foo4 = Foo::Foo();
</code></pre>
<p>Uses copy-initialization to create a <code>Foo</code> object called <code>foo4</code> in automatic storage.</p>
<pre><code> /* 5 */ Bar* bar1 = new Bar ( *new Foo() );
</code></pre>
<p>Uses <code>Bar</code>'s conversion constructor to create an object of type <code>Bar</code> in dynamic storage. <code>bar1</code> is a pointer to it.</p>
<pre><code> /* 6 */ Bar* bar2 = new Bar ( *new Foo );
</code></pre>
<p>Same as before.</p>
<pre><code> /* 7 */ Bar* bar3 = new Bar ( Foo foo5 );
</code></pre>
<p>This is just invalid syntax. You can't declare a variable there.</p>
<pre><code> /* 8 */ Bar* bar3 = new Bar ( Foo::Foo() );
</code></pre>
<p>Would work and work by the same principle to 5 and 6 if <code>bar3</code> wasn't declared on in 7.</p>
<p><strong>5 & 6</strong> contain memory leaks.</p>
<p>Syntax like <code>new Bar ( Foo::Foo() );</code> is not usual. It's usually <code>new Bar ( (Foo()) );</code> - <del>extra parenthesis account for most-vexing parse.</del> (corrected)</p> |
12,059,509 | Create a single executable from a Python project | <p>I want to create a single executable from my Python project. A user should be able to download and run it without needing Python installed. If I were just distributing a package, I could use pip, wheel, and PyPI to build and distribute it, but this requires that the user has Python and knows how to install packages. What can I use to build a self-contained executable from a Python project?</p> | 12,059,644 | 3 | 0 | null | 2012-08-21 16:47:58.143 UTC | 118 | 2022-08-02 23:40:16.203 UTC | 2017-01-18 14:21:42.793 UTC | null | 400,617 | null | 972,706 | null | 1 | 162 | python|compilation|exe|packaging|software-distribution | 124,500 | <p>There are several different ways of doing this.</p>
<hr />
<p>The first -- and likely most common -- way is to use "freeze" style programs. These programs work by bundling together Python and your program, essentially combining them into a single executable:</p>
<ul>
<li><p><strong>PyInstaller:</strong></p>
<p><a href="https://www.pyinstaller.org/" rel="noreferrer">Website</a> || <a href="https://github.com/pyinstaller/pyinstaller" rel="noreferrer">Repo</a> || <a href="https://pypi.python.org/pypi/PyInstaller" rel="noreferrer">PyPi</a></p>
<p>Supports Python 3.7 - 3.10 on Windows, Mac, and Linux.</p>
</li>
<li><p><strong>cx_Freeze:</strong></p>
<p><a href="https://cx-freeze.readthedocs.io/en/latest/" rel="noreferrer">Website</a> || <a href="https://github.com/marcelotduarte/cx_Freeze" rel="noreferrer">Repo</a> || <a href="https://pypi.python.org/pypi/cx_Freeze" rel="noreferrer">PyPi</a></p>
<p>Supports Python 3.6 - 3.10 on Windows, Mac, and Linux.</p>
</li>
<li><p><strong>py2exe:</strong></p>
<p><a href="https://www.py2exe.org/" rel="noreferrer">Website</a> || <a href="https://github.com/py2exe/py2exe" rel="noreferrer">Repo</a> || <a href="https://pypi.python.org/pypi/py2exe/" rel="noreferrer">PyPi</a></p>
<p>Supports Python 3.7 - 3.10 on Windows only.</p>
</li>
<li><p><strong>py2app:</strong></p>
<p><a href="https://py2app.readthedocs.io/en/latest/" rel="noreferrer">Website</a> || <a href="https://github.com/ronaldoussoren/py2app" rel="noreferrer">Repo</a> || <a href="https://pypi.python.org/pypi/py2app/" rel="noreferrer">PyPi</a></p>
<p>Supports Python 3.6 - 3.10 on Macs only.</p>
</li>
</ul>
<p>The main thing to keep in mind is that these types of programs will generally only produce an exe for the operating system you run it in. So for example, running Pyinstaller in Windows will produce a Windows exe, but running Pyinstaller in Linux will produce a Linux exe. If you want to produce an exe for multiple operating systems, you will have to look into using virtual machines or something like <a href="https://www.winehq.org/" rel="noreferrer">Wine</a>.</p>
<hr />
<p>Of course, that's not the only way of doing things:</p>
<ul>
<li><p><strong>pynsist:</strong></p>
<p><a href="http://pynsist.readthedocs.org/en/latest/" rel="noreferrer">Website</a> || <a href="https://github.com/takluyver/pynsist" rel="noreferrer">Repo</a> || <a href="https://pypi.python.org/pypi/pynsist" rel="noreferrer">PyPi</a></p>
<p>Pynsist will create a Windows installer for your program which will directly install Python on the user's computer instead of bundling it with your code and create shortcuts that link to your Python script.</p>
<p>The pynsist tool itself requires Python 3.5+ to run, but supports bundling any version of Python with your program.</p>
<p>Pynsist will create Windows installers only, but can be run from Windows, Mac, and Linux. See <a href="http://pynsist.readthedocs.org/en/latest/faq.html#building-on-other-platforms" rel="noreferrer">their FAQ</a> for more details.</p>
</li>
<li><p><strong>Nuitka:</strong></p>
<p><a href="http://nuitka.net/" rel="noreferrer">Website</a> || <a href="https://github.com/kayhayen/Nuitka" rel="noreferrer">Repo (Github mirror)</a> || <a href="https://pypi.python.org/pypi/Nuitka/" rel="noreferrer">PyPi</a></p>
<p>Nuitka will literally compile your Python code and produce an exe (as opposed to the other projects, which simply include Python) to try and speed up your code. As a side effect, you'll also get a handy exe you can distribute. Note that you need to have a <a href="http://nuitka.net/doc/user-manual.html#requirements" rel="noreferrer">C++ compiler</a> available on your system.</p>
<p>Supports Python 2.6 - 2.7 and Python 3.3 - 3.10 on Windows, Mac, and Linux.</p>
</li>
<li><p><strong>cython:</strong></p>
<p><a href="http://cython.org/" rel="noreferrer">Website</a> || <a href="https://github.com/cython/cython" rel="noreferrer">Repo</a> || <a href="https://pypi.python.org/pypi/Cython/" rel="noreferrer">PyPi</a></p>
<p>Cython is similar to Nuitka in that it is a Python compiler. However, instead of directly compiling your code, it'll compile it to C. You can then take that C code and <a href="https://stackoverflow.com/q/2581784/646543">turn your code into an exe</a>. You'll need to have a C compiler available on your system.</p>
<p>Supports Python 2.7 and Python 3.3 - 3.11 on Windows, Mac, and Linux.</p>
</li>
</ul>
<hr />
<p>My personal preference is to use PyInstaller since it was the easiest for me to get up and running, was designed to work nicely with various popular libraries such as numpy or pygame, and has great compatibility with various OSes and Python versions.</p>
<p>However, I've also successfully built various exes using cx_Freeze without too much difficulty, so you should also consider trying that program out.</p>
<p>I haven't yet had a chance to to try pynist, Nuitka, or Cython extensively, but they seem like pretty interesting and innovative solutions. If you run into trouble using the first group of programs, it might be worthwhile to try one of these three. Since they work fundamentally differently then the Pyinstaller/cx_freeze-style programs, they might succeed in those odd edge cases where the first group fails.</p>
<p>In particular, I think pynist is a good way of sidestepping the entire issue of distributing your code altogether: Macs and Linux already have native support for Python, and just installing Python on Windows might genuinely be the cleanest solution. (The downside is now that you need to worry about targeting multiple versions of Python + installing libraries).</p>
<p>Nuitka and Cython (in my limited experience) seem to work fairly well. Again, I haven't tested them extensively myself, and so my main observation is that they seem to take much longer to produce an exe then the "freeze" style programs do.</p>
<hr />
<p>All this being said, converting your Python program into an executable isn't necessarily the only way of distributing your code. To learn more about what other options are available, see the following links:</p>
<ul>
<li><a href="https://packaging.python.org/overview/#packaging-python-applications" rel="noreferrer">https://packaging.python.org/overview/#packaging-python-applications</a></li>
<li><a href="https://docs.python-guide.org/shipping/packaging/#for-linux-distributions" rel="noreferrer">https://docs.python-guide.org/shipping/packaging/#for-linux-distributions</a></li>
</ul> |
24,250,582 | Set a specific bit in an int | <p>I need to mask certain string values read from a database by setting a specific bit in an int value for each possible database value. For example, if the database returns the string "value1" then the bit in position 0 will need to be set to 1, but if the database returns "value2" then the bit in position 1 will need to be set to 1 instead.</p>
<p>How can I ensure each bit of an int is set to 0 originally and then turn on just the specified bit?</p> | 24,250,656 | 4 | 8 | null | 2014-06-16 19:14:47.98 UTC | 5 | 2021-04-11 11:34:19.197 UTC | null | null | null | null | 952,880 | null | 1 | 33 | c#|bit-manipulation | 47,871 | <p>If you have an int value "<em>intValue</em>" and you want to set a specific bit at position "<em>bitPosition</em>", do something like:</p>
<pre><code>intValue = intValue | (1 << bitPosition);
</code></pre>
<p>or shorter:</p>
<pre><code>intValue |= 1 << bitPosition;
</code></pre>
<p><BR>
If you want to reset a bit (i.e, set it to zero), you can do this:</p>
<pre><code>intValue &= ~(1 << bitPosition);
</code></pre>
<p>(The operator <code>~</code> reverses each bit in a value, thus <code>~(1 << bitPosition)</code> will result in an <em>int</em> where every bit is <em>1</em> except the bit at the given <em>bitPosition</em>.)</p> |
3,325,762 | Loading Image to Filestream | <p>I am loading an image using </p>
<pre><code>OpenFileDialog open = new OpenFileDialog();
</code></pre>
<p>After I select the file, "open" is populated with several items, including the path.</p>
<p>Now I would like to load the file into a filestream (or something similar) to be sent via a webservice... is this possible?</p>
<p>thanks</p> | 3,325,781 | 3 | 3 | null | 2010-07-24 16:00:54.51 UTC | 1 | 2010-07-24 16:12:26.577 UTC | null | null | null | null | 164,497 | null | 1 | 10 | c#|filestream|openfiledialog | 47,613 | <p>You can open the file with <a href="http://msdn.microsoft.com/en-us/library/47ek66wy.aspx" rel="noreferrer"><code>FileStream</code></a>:</p>
<pre><code>FileStream file = new FileStream("path to file", FileMode.Open);
</code></pre>
<p>You can then pass this through to the web service http context <a href="http://msdn.microsoft.com/en-us/library/system.web.httpresponse.outputstream.aspx" rel="noreferrer">Response.OutputStream</a> property. You will still need to set the correct mime type and various headers, but this works well:</p>
<pre><code>HttpContext.Current.Response.OutputStream = file;
</code></pre>
<p>Having said that, the easiest way to send a file from a web service (or web app) is to use the <a href="http://msdn.microsoft.com/en-us/library/dyfzssz9.aspx" rel="noreferrer">Response.WriteFile</a> method:</p>
<pre><code>Response.WriteFile("Path To File");
</code></pre> |
3,320,674 | Spring: how do I inject an HttpServletRequest into a request-scoped bean? | <p>I'm trying to set up a <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-scopes-other" rel="noreferrer">request-scoped bean</a> in Spring.</p>
<p>I've successfully set it up so the bean is created once per request. Now, it needs to access the HttpServletRequest object.</p>
<p>Since the bean is created once per request, I figure the container can easily inject the request object in my bean. How can I do that ?</p> | 3,324,233 | 3 | 0 | null | 2010-07-23 17:16:43.813 UTC | 45 | 2019-09-10 01:00:40.793 UTC | 2010-07-24 07:28:24.84 UTC | null | 21,234 | null | 15,649 | null | 1 | 118 | java|spring|servlets | 132,509 | <p>Request-scoped beans can be autowired with the request object.</p>
<pre><code>private @Autowired HttpServletRequest request;
</code></pre> |
36,896,279 | How to tell Rubocop to ignore a specific directory or file | <p>My project is extending open-source classes from a third-party gem that we don't want to hold to the same coding standards as our own code. Refactoring the gem code isn't a viable option. We just want Rubocop to ignore the copied code.</p>
<p>How can I instruct Rubocop to completely ignore a file or directory?</p> | 36,896,588 | 6 | 8 | null | 2016-04-27 17:00:29.733 UTC | 7 | 2021-12-22 03:25:19.767 UTC | 2016-05-02 13:23:07.343 UTC | null | 998,495 | null | 998,495 | null | 1 | 107 | ruby|rubocop | 59,104 | <p>As per orde's comment with the link to <a href="http://rubocop.readthedocs.io/en/latest/configuration/#includingexcluding-files">the manual</a> I found .rubocop.yml and added the following:</p>
<pre><code>AllCops:
Exclude:
- 'path/to/excluded/file.rb'
</code></pre>
<p>where the path is relative to .rubocop.yml</p> |
22,856,215 | What is the meaning of the planned "private protected" C# access modifier? | <p>As part of the <a href="https://github.com/dotnet/roslyn" rel="noreferrer">Roslyn</a> documentation on GitHub, there's a page called <a href="https://github.com/dotnet/roslyn/wiki/Languages-features-in-C%23-6-and-VB-14" rel="noreferrer">Language feature implementation status</a>, with planned language features for C# and VB.</p>
<p>One feature I couldn't wrap my head around was <code>private protected</code> access modifier:</p>
<pre><code>private protected string GetId() { … }
</code></pre>
<p>There is also a page of <a href="https://github.com/dotnet/csharplang/tree/master/meetings/2014" rel="noreferrer">C# Language Design Notes</a>, which explains many new features, but not this one.</p>
<p>Eric Lippert said in a <a href="https://stackoverflow.com/questions/1063901/why-is-internal-protected-not-more-restrictive-than-internal#comment876691_1063901">comment</a>:</p>
<blockquote>
<p>Your error is in thinking of the modifiers as increasing restrictions. The modifiers in fact always decrease restrictions. Remember, things are "private" by default; only by adding modifiers do you make them less restricted.</p>
</blockquote>
<p>What is the meaning of <code>private protected</code>? When might I use it?</p> | 22,857,053 | 6 | 5 | null | 2014-04-04 07:24:11.503 UTC | 35 | 2022-05-13 07:04:34.407 UTC | 2017-12-18 12:17:30.68 UTC | null | 7,586 | null | 7,586 | null | 1 | 136 | c#|access-modifiers|c#-6.0|c#-7.2 | 12,480 | <p>According to "<a href="http://books.google.ro/books?id=-sjg09Crh40C&pg=PA1699&lpg=PA1699&dq=%22protected%20private%22%20c#&source=bl&ots=g0zvFvndSU&sig=9_6aNFTgLOTyV5Jjl5nW3gyU5DA&hl=ro&sa=X&ei=MWc-U-LwLovnygPhhIKIDg&ved=0CHgQ6AEwBw#v=onepage&q=%22protected%20private%22%20c#&f=false" rel="noreferrer">Professional C# 2008</a>" by De Bill Evjen and Jay Glynn, page 1699:</p>
<blockquote>
<p>private protected - "only derived types within the current assembly"<br></p>
</blockquote>
<p>C++/CLI has a similar feature - <a href="http://msdn.microsoft.com/en-us/library/ke3a209d.aspx#BKMK_Member_visibility" rel="noreferrer">Define and Consume Classes and Structs (C++/CLI) > Member visibility</a>:</p>
<blockquote>
<p><code>private protected</code> -or- <code>protected private</code> - Member is protected inside the assembly but private outside the assembly.</p>
</blockquote> |
20,572,016 | JavaScript String concatenation behavior with null or undefined values | <p>As you may know, in JavaScript <code>'' + null = "null"</code> and <code>'' + undefined = "undefined"</code> (in most browsers I can test: Firefox, Chrome and IE). I would like to know the origin of this oddity (what the heck was in the head on Brendan Eich?!) and if there is any aim for changing it in a future version of ECMA. It's indeed pretty frustrating having to do <code>'sthg' + (var || '')</code> for concatenating Strings with variables and using a third party framework like <em>Underscore</em> or other for that is using a hammer for jelly nail pounding.</p>
<p><strong>Edit:</strong></p>
<p>To meet the criteria required by StackOverflow and clarify my question, it is a threefold one:</p>
<ul>
<li>What is the history behind the oddity that makes JS converting <code>null</code> or <code>undefined</code> to their string value in <code>String</code> concatenation?</li>
<li>Is there any chance for a change in this behavior in future ECMAScript versions?</li>
<li>What is the prettiest way to concatenate <code>String</code> with potential <code>null</code> or <code>undefined</code> object without falling into this problem (getting some <code>"undefined"</code> of <code>"null"</code> in the middle of the String)? By the subjective criteria <em>prettiest</em>, I mean: short, clean and effective. No need to say that <code>'' + (obj ? obj : '')</code> is not really pretty…</li>
</ul> | 26,767,630 | 7 | 4 | null | 2013-12-13 17:03:06.267 UTC | 12 | 2021-10-01 21:38:11.953 UTC | 2013-12-24 09:31:06.247 UTC | null | 256,561 | null | 256,561 | null | 1 | 93 | javascript|null|undefined|string-concatenation | 85,302 | <blockquote>
<p>What is the prettiest way to concatenate String with potential null or undefined object without falling into this problem [...]?</p>
</blockquote>
<p>There are several ways, and you partly mentioned them yourself. To make it short, the <em>only</em> clean way I can think of is a function:</p>
<pre><code>const Strings = {};
Strings.orEmpty = function( entity ) {
return entity || "";
};
// usage
const message = "This is a " + Strings.orEmpty( test );
</code></pre>
<p>Of course, you can (and should) change the actual implementation to suit your needs. And this is already why I think this method is superior: it introduced encapsulation.</p>
<p>Really, you only have to ask what the "prettiest" way is, if you don't have encapsulation. You ask yourself this question because you <em>already know</em> that you are going to get yourself into a place where you cannot change the implementation anymore, so you want it to be perfect right away. But that's the thing: requirements, views and even envrionments change. They evolve. So why not allow yourself to change the implementation with as little as adapting one line and perhaps one or two tests?</p>
<p>You could call this cheating, because it doesn't really answer how to implement the actual logic. But that's my point: it doesn't matter. Well, maybe a little. But really, there is no need to worry because of how simple it would be to change. And since it's not inlined, it also looks a lot prettier – whether or not you implement it this way or in a more sophisticated way.</p>
<p>If, throughout your code, you keep repeating the <code>||</code> inline, you run into two problems:</p>
<ul>
<li>You duplicate code.</li>
<li>And because you duplicate code, you make it hard to maintain and change in the future.</li>
</ul>
<p>And these are two points commonly known to be anti-patterns when it comes to high-quality software development.</p>
<p>Some people will say that this is too much overhead; they will talk about performance. It's non-sense. For one, this barely adds overhead. If this is what you are worried about, you chose the wrong language. Even jQuery uses functions. People need to get over micro-optimization.</p>
<p>The other thing is: you can use a code "compiler" = minifier. Good tools in this area will try to detect which statements to inline during the compilation step. This way, you keep your code clean and maintainable and can still get that last drop of performance if you still believe in it or really do have an environment where this matters.</p>
<p>Lastly, have some faith in browsers. They will optimize code and they do a pretty darn good job at it these days.</p> |
20,481,058 | Find pathname from dlopen handle on OSX | <p>I have <code>dlopen()</code>'ed a library, and I want to invert back from the handle it passes to me to the full pathname of shared library. On Linux and friends, I know that I can use <code>dlinfo()</code> to get the linkmap and iterate through those structures, but I can't seem to find an analogue on OSX. The closest thing I can do is to either:</p>
<ul>
<li><p>Use <code>dyld_image_count()</code> and <code>dyld_get_image_name()</code>, iterate over all the currently opened libraries and hope I can guess which one corresponds to my handle</p></li>
<li><p>Somehow find a symbol that lives inside of the handle I have, and pass that to <code>dladdr()</code>.</p></li>
</ul>
<p>If I have apriori knowledge as to a symbol name inside of the library I just opened, I can <code>dlsym()</code> that and then use <code>dladdr()</code>. That works fine. But in the general case where I have no idea what is inside this shared library, I would need to be able to enumerate symbols to do that, which I don't know how to do either.</p>
<p>So any tips on how to lookup the pathname of a library from its <code>dlopen</code> handle would be very much appreciated. Thanks!</p> | 30,293,362 | 2 | 6 | null | 2013-12-09 21:21:44.3 UTC | 10 | 2015-05-17 23:58:12.22 UTC | null | null | null | null | 230,778 | null | 1 | 14 | c|macos|dyld | 3,150 | <p>After about a year of using the solution provided by 0xced, we discovered an alternative method that is simpler and avoids one (rather rare) failure mode; specifically, because 0xced's code snippet iterates through each dylib currently loaded, finds the first exported symbol, attempts to resolve it in the dylib currently being sought, and returns positive if that symbol is found in that particular dylib, you can have false positives if the first exported symbol from an arbitrary library happens to be present inside of the dylib you're currently searching for.</p>
<p>My solution was to use <code>_dyld_get_image_name(i)</code> to get the absolute path of each image loaded, <code>dlopen()</code> that image, and compare the handle (after masking out any mode bits set by <code>dlopen()</code> due to usage of things like <code>RTLD_FIRST</code>) to ensure that this dylib is actually the same file as the handle passed into my function.</p>
<p>The complete function <a href="https://github.com/JuliaLang/julia/blob/0027ed143e90d0f965694de7ea8c692d75ffa1a5/src/sys.c#L572-L583" rel="noreferrer">can be seen here</a>, as a part of the Julia Language, with the relevant portion copied below:</p>
<pre><code>// Iterate through all images currently in memory
for (int32_t i = _dyld_image_count(); i >= 0 ; i--) {
// dlopen() each image, check handle
const char *image_name = _dyld_get_image_name(i);
uv_lib_t *probe_lib = jl_load_dynamic_library(image_name, JL_RTLD_DEFAULT);
void *probe_handle = probe_lib->handle;
uv_dlclose(probe_lib);
// If the handle is the same as what was passed in (modulo mode bits), return this image name
if (((intptr_t)handle & (-4)) == ((intptr_t)probe_handle & (-4)))
return image_name;
}
</code></pre>
<p>Note that functions such as <code>jl_load_dynamic_library()</code> are wrappers around <code>dlopen()</code> that return <code>libuv</code> types, but the spirit of the code remains the same.</p> |
26,070,547 | Decoding base64 from POST to use in PIL | <p>I'm making a simple API in Flask that accepts an image encoded in base64, then decodes it for further processing using Pillow.</p>
<p>I've looked at some examples (<a href="https://stackoverflow.com/questions/19908975/loading-base64-string-into-python-image-library">1</a>, <a href="https://stackoverflow.com/questions/3715493/encoding-an-image-file-with-base64">2</a>, <a href="https://stackoverflow.com/questions/19910845/strange-ioerror-when-opening-base64-string-in-pil">3</a>), and I think I get the gist of the process, but I keep getting an error where Pillow can't read the string I gave it.</p>
<p>Here's what I've got so far:</p>
<pre><code>import cStringIO
from PIL import Image
import base64
data = request.form
image_string = cStringIO.StringIO(base64.b64decode(data['img']))
image = Image.open(image_string)
</code></pre>
<p>which gives the error:</p>
<pre><code>IOError: cannot identify image file <cStringIO.StringIO object at 0x10f84c7a0>
</code></pre> | 26,079,673 | 3 | 5 | null | 2014-09-27 01:56:50.373 UTC | 13 | 2020-09-21 06:37:40.717 UTC | 2017-05-23 12:10:35.767 UTC | null | -1 | null | 2,043,886 | null | 1 | 55 | python|flask|base64|python-imaging-library|pillow | 51,287 | <p>You should try something like:</p>
<pre><code>from PIL import Image
from io import BytesIO
import base64
data['img'] = '''R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLl
N48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw=='''
im = Image.open(BytesIO(base64.b64decode(data['img'])))
</code></pre>
<p>Your <code>data['img']</code> string should not include the HTML tags or the parameters <code>data:image/jpeg;base64</code> that are in the example JSFiddle.</p>
<p>I've changed the image string for an example I took from Google just for readability purposes.</p> |
11,293,994 | How to convert a UTF-8 string into Unicode? | <p>I have string that displays UTF-8 encoded characters, and I want to convert it back to Unicode.</p>
<p>For now, my implementation is the following:</p>
<pre><code>public static string DecodeFromUtf8(this string utf8String)
{
// read the string as UTF-8 bytes.
byte[] encodedBytes = Encoding.UTF8.GetBytes(utf8String);
// convert them into unicode bytes.
byte[] unicodeBytes = Encoding.Convert(Encoding.UTF8, Encoding.Unicode, encodedBytes);
// builds the converted string.
return Encoding.Unicode.GetString(encodedBytes);
}
</code></pre>
<p>I am playing with the word <code>"déjà"</code>. I have converted it into UTF-8 through this <a href="http://www.cafewebmaster.com/online_tools/utf8_encode" rel="noreferrer">online tool</a>, and so I started to test my method with the string <code>"déjÃ"</code>.</p>
<p>Unfortunately, with this implementation the string just remains the same.</p>
<p>Where am I wrong?</p> | 11,300,580 | 4 | 13 | null | 2012-07-02 12:47:16.26 UTC | 7 | 2016-10-13 17:37:28.53 UTC | 2012-07-02 12:55:54.65 UTC | null | 177,596 | null | 177,596 | null | 1 | 8 | c#|string|unicode|utf-8 | 143,628 | <p>So the issue is that UTF-8 code unit values have been stored as a sequence of 16-bit code units in a C# <code>string</code>. You simply need to verify that each code unit is within the range of a byte, copy those values into bytes, and then convert the new UTF-8 byte sequence into UTF-16.</p>
<pre><code>public static string DecodeFromUtf8(this string utf8String)
{
// copy the string as UTF-8 bytes.
byte[] utf8Bytes = new byte[utf8String.Length];
for (int i=0;i<utf8String.Length;++i) {
//Debug.Assert( 0 <= utf8String[i] && utf8String[i] <= 255, "the char must be in byte's range");
utf8Bytes[i] = (byte)utf8String[i];
}
return Encoding.UTF8.GetString(utf8Bytes,0,utf8Bytes.Length);
}
DecodeFromUtf8("d\u00C3\u00A9j\u00C3\u00A0"); // déjà
</code></pre>
<p>This is easy, however it would be best to find the root cause; the location where someone is copying UTF-8 code units into 16 bit code units. The likely culprit is somebody converting bytes into a C# <code>string</code> using the wrong encoding. E.g. <code>Encoding.Default.GetString(utf8Bytes, 0, utf8Bytes.Length)</code>.</p>
<hr>
<p>Alternatively, if you're sure you know the incorrect encoding which was used to produce the string, and that incorrect encoding transformation was lossless (usually the case if the incorrect encoding is a single byte encoding), then you can simply do the inverse encoding step to get the original UTF-8 data, and then you can do the correct conversion from UTF-8 bytes:</p>
<pre><code>public static string UndoEncodingMistake(string mangledString, Encoding mistake, Encoding correction)
{
// the inverse of `mistake.GetString(originalBytes);`
byte[] originalBytes = mistake.GetBytes(mangledString);
return correction.GetString(originalBytes);
}
UndoEncodingMistake("d\u00C3\u00A9j\u00C3\u00A0", Encoding(1252), Encoding.UTF8);
</code></pre> |
10,865,795 | Changing Ownership of a directory in OS X | <p>I've installed homebrew, and am trying to change the write permissisons for the /usr/local/include directory.</p>
<p>When I run 'brew doctor', I get this error message: </p>
<blockquote>
<p>Error: The /usr/local directory is not writable. Even if this
directory was writable when you installed Homebrew, other software may
change permissions on this directory. Some versions of the "InstantOn"
component of Airfoil are known to do this.</p>
<p>You should probably change the ownership and permissions of /usr/local
back to your user account.</p>
</blockquote>
<p>I tried doing that with chown, but I'm pretty new at this and don't think I was running it correctly. I ran:</p>
<pre><code>chown myusername /usr/local/include
</code></pre>
<p>I didn't get any error message, but when I run brew doctor it says I still lack permission to write to /usr/local/include.</p>
<p>Any help would be greatly appreciated!</p>
<p><strong>Edit:</strong> </p>
<p>I'm getting an "operation not permitted" error.</p>
<p><code>cd /usr</code></p>
<p><code>chown myusername local</code></p>
<p>chown: local: Operation not permitted</p> | 10,866,139 | 6 | 0 | null | 2012-06-02 20:43:15.783 UTC | 2 | 2019-07-26 11:02:54.957 UTC | 2012-06-02 21:10:31.34 UTC | null | 1,144,186 | null | 1,144,186 | null | 1 | 14 | macos|homebrew|chown | 40,313 | <p>On my system, <code>/usr/local</code> is owned by <code>root:admin</code> and is <code>rwxrwxr-x</code>. My user is a member of the <code>admin</code> group, thus has write permissions. I haven't messed with ownership and permissions there, and my Homebrew installation is not complaining, so I assume my setup fits its requirements.</p>
<p>Check the ownership of your <code>/usr/local</code>; if it is owned by group <code>admin</code>, check if your non-adminsitrator account is a member of that group.</p> |
10,865,202 | Ways to stop people from uploading GIFs with injections in them? | <p>I have a PHP website where people can fill out help-tickets. It allows them to upload screenshots for their ticket. I allow gif, psd, bmp, jpg, png, tif to be uploaded. Upon receiving the upload, the PHP script ignores the file extension. It identifies the filetype using only the MIME information, which for these filetypes is always stored within the first 12 bytes of the file.</p>
<p>Someone uploaded several GIFs, which when viewed with a browser, the browser said it was invalid, and my virus scanner alerted me that it was a injection (or something like that). See below for a zip file containing these GIFs.</p>
<p>I don't think only checking header info is adequate. I have heard that an image can be completely valid, but also contain exploit code.</p>
<p>So I have two basic questions:</p>
<ol>
<li>Does anyone know how they did injected bad stuff into a GIF (<em>while still keeping a valid GIF MIME type</em>)? If I know this, maybe I can check for it at upload time.</li>
<li>How can I prevent someone from uploading files like this?
<ul>
<li>I am on shared hosting so I can't install a server-side virus
scanner.</li>
<li>Submitting the info to a online virus scanning website
might be too slow.</li>
<li>Is there any way to check myself using a PHP class that checks for these things?</li>
<li>Will resize the image using GD fail if it's not valid? Or would the exploit still slip through and be in the resized image? If it fails, that would be ideal because then I could use resizing as a technique to see if they are valid.</li>
</ul></li>
</ol>
<hr>
<p><strong>Update:</strong> Everyone, thanks for replying so far. I am attempting to look on the server for the GIFs that were uploaded. I will update this post if I find them.</p>
<p><strong>Update 2:</strong> I located the GIFs for anyone interested. I put them in a zip file encrypted with password "123". It is located here (be careful there are multiple "Download" buttons on this hosting site -- some of them are for ads) <a href="http://www.filedropper.com/badgifs" rel="noreferrer">http://www.filedropper.com/badgifs</a>. The one called 5060.gif is flagged by my antivirus as a trojan (TR/Graftor.Q.2). I should note that these files were upload prior to me implementing the MIME check of the first 12 bytes. So now, I am safe for these particular ones. But I'd still like to know how to detect an exploit hiding behind a correct MIME type.</p>
<hr>
<p><strong>Important clarification:</strong> <em>I'm only concerned about the risk to the PC who downloads these files to look at them.</em> The files are not a risk to my server. They won't be executed. They are stored using a clean name (a hex hash output) with extension of ".enc" and I save them to disk in an encrypted state using an fwrite filter:</p>
<pre><code>// Generate random key to encrypt this file.
$AsciiKey = '';
for($i = 0; $i < 20; $i++)
$AsciiKey .= chr(mt_rand(1, 255));
// The proper key size for the encryption mode we're using is 256-bits (32-bytes).
// That's what "mcrypt_get_key_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC)" says.
// So we'll hash our key using SHA-256 and pass TRUE to the 2nd parameter, so we
// get raw binary output. That will be the perfect length for the key.
$BinKey = hash('SHA256', '~~'.TIME_NOW.'~~'.$AsciiKey.'~~', true);
// Create Initialization Vector with block size of 128 bits (AES compliant) and CBC mode
$InitVec = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
$Args = array('iv' => $InitVec, 'key' => $BinKey, 'mode' => 'cbc');
// Save encoded file in uploads_tmp directory.
$hDest = fopen(UPLOADS_DIR_TMP.'/'.$Hash.'.enc', 'w');
stream_filter_append($hDest, 'mcrypt.rijndael-128', STREAM_FILTER_WRITE, $Args);
fwrite($hDest, $Data);
fclose($hDest);
</code></pre> | 10,865,274 | 7 | 9 | null | 2012-06-02 19:19:13.297 UTC | 9 | 2016-05-10 09:36:25.44 UTC | 2012-06-02 21:56:02.41 UTC | null | 856,987 | null | 856,987 | null | 1 | 18 | php|security|image-processing|gd|code-injection | 5,198 | <p>As for the <strong>first question</strong>, you'll never really know if you're not able to retrieve any logs or the images in question, because there are many things these exploit may have targeted and depending on what's the target the way the exploit was put into the file can be completely different.</p>
<p><strong>Edit:</strong> <em>W32/Graftor</em> is a <a href="https://www.f-secure.com/v-descs/trojan_w32_graftor.shtml" rel="nofollow">generic name</a> for programs that appear to have trojan-like characteristics.</p>
<p>After opening the file <code>5060.gif</code> in a hex editor, I noticed the program is actually a <a href="http://img560.imageshack.us/img560/3516/izprog1.png" rel="nofollow">renamed windows program</a>. Although it's not a browser exploit and thus harmless unless it's actually opened and executed, you'll have to make sure it isn't served with the MIME type defined by the uploader because a user may still be tricked into opening the program; see the answer to the second question.</p>
<p>As for the <strong>second question</strong>: to prevent any exploit code from being run or a user, you'll have to make sure all files are stored with a safe extension in the filename so they are served with the correct MIME type. For example, you can use this regular expression to check the file name:</p>
<pre><code>if(!preg_match ( '/\\.(gif|p(sd|ng)|tiff?|jpg)$/' , $fileName)){
header("415 Unsupported Media Type");
die("File type not allowed.");
}
</code></pre>
<p>Also make sure you're serving the files with the correct Content Type; make sure you don't use the content type specified with the uploaded file when serving the file to the user. If you rely on the Content-Type specified by the uploader, the file may be served as <code>text/html</code> or anything similar and will be parsed by the users' browser as such.</p>
<p>Please note that this only protects against malicious files exploiting vulnerabilities in the users' browser, the image parser excluded.</p>
<p>If you're trying to prevent exploits against the server you'll have to make sure that you won't let the PHP parser execute the contents of the image and that the image library you are using to process the image does not have any known vulnerabilities.</p>
<p>Also note that this code does not defend you against images that contain an exploit for the image parser used by the users browser; to defend against this, you can check if <code>getimagesize()</code> evaluates to true as suggested by Jeroen.</p>
<p>Note that using <code>getimagesize()</code> alone isn't sufficient if you don't check file names and make sure files are served with the correct <code>Content-Type</code> header, because completely valid images can have HTML / PHP code embedded inside comments.</p> |
11,279,898 | Binding event to chosen select | <p>I have this code for a select box which is being displayed by the Chosen jQuery plugin. What I am trying to achieve is to get the value from the current item that has been selected:</p>
<pre><code><div>
<select id="schedule_event" name="schedule[event]" style="display: none; " class="chzn-done"><option value="Game" selected="selected">Game</option>
<option value="Event">Event</option>
<option value="Training">Training</option>
</select>
<div id="schedule_event_chzn" class="chzn-container chzn-container-single chzn-container-active" style="width: 854px; ">
<a href="javascript:void(0)" class="chzn-single chzn-single-with-drop" tabindex="-1">
<span>Game</span>
<div></div>
</a>
<div class="chzn-drop" style="width: 849px; top: 27px; left: 0px; ">
<div class="chzn-search">
<input type="text" autocomplete="off" style="width: 814px; " tabindex="0">
</div>
<ul class="chzn-results">
<li id="schedule_event_chzn_o_0" class="active-result result-selected highlighted" style="">Game</li>
<li id="schedule_event_chzn_o_1" class="active-result" style="">Event</li>
<li id="schedule_event_chzn_o_2" class="active-result" style="">Training</li>
</ul>
</div>
</div>
</div>
</code></pre>
<p>The JavaScript I'm using at the moment to find the current value is:</p>
<pre><code>$("#schedule_event").chosen().change( function() {
alert(+ $(this).text());
$('#' + $(this).val()).show();
});
</code></pre>
<p>However, I keep getting a 'NaN', ie no value.</p> | 11,279,925 | 2 | 2 | null | 2012-07-01 05:52:48.147 UTC | 2 | 2017-08-17 17:40:43.02 UTC | 2017-08-17 17:33:56.287 UTC | null | 4,660,897 | null | 1,448,378 | null | 1 | 19 | jquery|onchange|jquery-chosen|jquery-events | 50,346 | <p><strong>Code:</strong></p>
<pre><code>$(".chzn-select").chosen().change(function() {
alert(+$(this).val());
//$('#' + $(this).val()).show();
});
</code></pre>
<p><strong>Demo:</strong></p>
<p><strike>Working demo: <a href="http://jsfiddle.net/MM7wh/" rel="noreferrer">http://jsfiddle.net/MM7wh/</a></strike></p>
<h3>Edit (6th July 2015)</h3>
<p>cdns are changed now.</p>
<p>Working demo: <a href="http://jsfiddle.net/uk82dm5L/" rel="noreferrer">http://jsfiddle.net/uk82dm5L/</a></p>
<p>Please use <code>$(this).val()</code> instead of <code>.text()</code>.</p> |
11,446,254 | How to emulate SQLs rank functions in R? | <p>What is the R equivalent of rank functions like the Oracle <code>ROW_NUMBER()</code>, <code>RANK()</code>, or <code>DENSE_RANK()</code> ("assign integer values to the rows depending on their order"; see <a href="http://www.orafaq.com/node/55" rel="nofollow noreferrer">http://www.orafaq.com/node/55</a>)? </p>
<p>I agree that the functionality of each function can potentially be achieved in an ad-hoc fashion. But my main concern is the performance. It would be good to avoid using join or indexing access, for the sake of memory and speed.</p> | 11,448,652 | 5 | 2 | null | 2012-07-12 06:38:38.593 UTC | 17 | 2020-12-04 20:19:59.017 UTC | 2020-04-19 10:00:52.497 UTC | null | 1,851,712 | null | 1,519,852 | null | 1 | 21 | sql|r|data.table|dplyr|dense-rank | 16,884 | <p>The <code>data.table</code> package, especially starting with version 1.8.1, offers much of the functionality of partition in SQL terms. <code>rank(x, ties.method = "min")</code> in R is similar to Oracle <code>RANK()</code>, and there's a way using factors (described below) to mimic the <code>DENSE_RANK()</code> function. A way to mimic <code>ROW_NUMBER</code> should be obvious by the end.</p>
<p>Here's an example: Load the latest version of <code>data.table</code> from R-Forge:</p>
<pre><code>install.packages("data.table",
repos= c("http://R-Forge.R-project.org", getOption("repos")))
library(data.table)
</code></pre>
<p>Create some example data:</p>
<pre><code>set.seed(10)
DT<-data.table(ID=seq_len(4*3),group=rep(1:4,each=3),value=rnorm(4*3),
info=c(sample(c("a","b"),4*2,replace=TRUE),
sample(c("c","d"),4,replace=TRUE)),key="ID")
> DT
ID group value info
1: 1 1 0.01874617 a
2: 2 1 -0.18425254 b
3: 3 1 -1.37133055 b
4: 4 2 -0.59916772 a
5: 5 2 0.29454513 b
6: 6 2 0.38979430 a
7: 7 3 -1.20807618 b
8: 8 3 -0.36367602 a
9: 9 3 -1.62667268 c
10: 10 4 -0.25647839 d
11: 11 4 1.10177950 c
12: 12 4 0.75578151 d
</code></pre>
<p>Rank each <code>ID</code> by decreasing <code>value</code> within <code>group</code> (note the <code>-</code> in front of <code>value</code> to denote decreasing order):</p>
<pre><code>> DT[,valRank:=rank(-value),by="group"]
ID group value info valRank
1: 1 1 0.01874617 a 1
2: 2 1 -0.18425254 b 2
3: 3 1 -1.37133055 b 3
4: 4 2 -0.59916772 a 3
5: 5 2 0.29454513 b 2
6: 6 2 0.38979430 a 1
7: 7 3 -1.20807618 b 2
8: 8 3 -0.36367602 a 1
9: 9 3 -1.62667268 c 3
10: 10 4 -0.25647839 d 3
11: 11 4 1.10177950 c 1
12: 12 4 0.75578151 d 2
</code></pre>
<p>For <code>DENSE_RANK()</code> with ties in the value being ranked, you could convert the value to a factor and then return the underlying integer values. For example, ranking each <code>ID</code> based on <code>info</code> within <code>group</code> (compare <code>infoRank</code> with <code>infoRankDense</code>):</p>
<pre><code>DT[,infoRank:=rank(info,ties.method="min"),by="group"]
DT[,infoRankDense:=as.integer(factor(info)),by="group"]
R> DT
ID group value info valRank infoRank infoRankDense
1: 1 1 0.01874617 a 1 1 1
2: 2 1 -0.18425254 b 2 2 2
3: 3 1 -1.37133055 b 3 2 2
4: 4 2 -0.59916772 a 3 1 1
5: 5 2 0.29454513 b 2 3 2
6: 6 2 0.38979430 a 1 1 1
7: 7 3 -1.20807618 b 2 2 2
8: 8 3 -0.36367602 a 1 1 1
9: 9 3 -1.62667268 c 3 3 3
10: 10 4 -0.25647839 d 3 2 2
11: 11 4 1.10177950 c 1 1 1
12: 12 4 0.75578151 d 2 2 2
</code></pre>
<p>p.s. Hi Matthew Dowle.</p>
<hr>
<p><strong>LEAD and LAG</strong></p>
<p>For imitating LEAD and LAG, start with the answer provided <a href="https://stackoverflow.com/a/10708124/1281189">here</a>. I would create a rank variable based on the order of IDs within groups. This wouldn't be necessary with the fake data as above, but if the IDs are not in sequential order within groups, then this would make life a bit more difficult. So here's some new fake data with non-sequential IDs:</p>
<pre><code>set.seed(10)
DT<-data.table(ID=sample(seq_len(4*3)),group=rep(1:4,each=3),value=rnorm(4*3),
info=c(sample(c("a","b"),4*2,replace=TRUE),
sample(c("c","d"),4,replace=TRUE)),key="ID")
DT[,idRank:=rank(ID),by="group"]
setkey(DT,group, idRank)
> DT
ID group value info idRank
1: 4 1 -0.36367602 b 1
2: 5 1 -1.62667268 b 2
3: 7 1 -1.20807618 b 3
4: 1 2 1.10177950 a 1
5: 2 2 0.75578151 a 2
6: 12 2 -0.25647839 b 3
7: 3 3 0.74139013 c 1
8: 6 3 0.98744470 b 2
9: 9 3 -0.23823356 a 3
10: 8 4 -0.19515038 c 1
11: 10 4 0.08934727 c 2
12: 11 4 -0.95494386 c 3
</code></pre>
<p>Then to get the values of the previous 1 record, use the <code>group</code> and <code>idRank</code> variables and subtract <code>1</code> from the <code>idRank</code> and use the <code>multi = 'last'</code> argument. To get the value from the record two entries above, subtract <code>2</code>.</p>
<pre><code>DT[,prev:=DT[J(group,idRank-1), value, mult='last']]
DT[,prev2:=DT[J(group,idRank-2), value, mult='last']]
ID group value info idRank prev prev2
1: 4 1 -0.36367602 b 1 NA NA
2: 5 1 -1.62667268 b 2 -0.36367602 NA
3: 7 1 -1.20807618 b 3 -1.62667268 -0.3636760
4: 1 2 1.10177950 a 1 NA NA
5: 2 2 0.75578151 a 2 1.10177950 NA
6: 12 2 -0.25647839 b 3 0.75578151 1.1017795
7: 3 3 0.74139013 c 1 NA NA
8: 6 3 0.98744470 b 2 0.74139013 NA
9: 9 3 -0.23823356 a 3 0.98744470 0.7413901
10: 8 4 -0.19515038 c 1 NA NA
11: 10 4 0.08934727 c 2 -0.19515038 NA
12: 11 4 -0.95494386 c 3 0.08934727 -0.1951504
</code></pre>
<p>For LEAD, add the appropriate offset to the <code>idRank</code> variable and switch to <code>multi = 'first'</code>:</p>
<pre><code>DT[,nex:=DT[J(group,idRank+1), value, mult='first']]
DT[,nex2:=DT[J(group,idRank+2), value, mult='first']]
ID group value info idRank prev prev2 nex nex2
1: 4 1 -0.36367602 b 1 NA NA -1.62667268 -1.2080762
2: 5 1 -1.62667268 b 2 -0.36367602 NA -1.20807618 NA
3: 7 1 -1.20807618 b 3 -1.62667268 -0.3636760 NA NA
4: 1 2 1.10177950 a 1 NA NA 0.75578151 -0.2564784
5: 2 2 0.75578151 a 2 1.10177950 NA -0.25647839 NA
6: 12 2 -0.25647839 b 3 0.75578151 1.1017795 NA NA
7: 3 3 0.74139013 c 1 NA NA 0.98744470 -0.2382336
8: 6 3 0.98744470 b 2 0.74139013 NA -0.23823356 NA
9: 9 3 -0.23823356 a 3 0.98744470 0.7413901 NA NA
10: 8 4 -0.19515038 c 1 NA NA 0.08934727 -0.9549439
11: 10 4 0.08934727 c 2 -0.19515038 NA -0.95494386 NA
12: 11 4 -0.95494386 c 3 0.08934727 -0.1951504 NA NA
</code></pre> |
11,211,292 | GitHub for Windows - is it open source? | <p>Is GitHub for Windows open source? If so, I can't seem to find the repository.</p> | 11,211,630 | 3 | 0 | null | 2012-06-26 15:56:57.803 UTC | 7 | 2017-06-16 01:41:39.733 UTC | 2013-01-13 22:20:20.443 UTC | null | 488,657 | null | 1,011,864 | null | 1 | 32 | github-for-windows | 6,022 | <p>According to Tom Preston-Werner, one of the GitHub founders, in his post <strong><a href="http://tom.preston-werner.com/2011/11/22/open-source-everything.html">"Open Source (Almost) Everything"</a></strong>, about the open-sourcing philosophy</p>
<blockquote>
<p>Don't open source anything that represents core business value. [...] <strong>Notice that everything we keep closed has specific business value that could be compromised by giving it away to our competitors</strong>. Everything we open is a general purpose tool that can be used by all kinds of people and companies to build all kinds of things.</p>
</blockquote>
<p>However, <strong>Hubot</strong>, previsouly a closed-source asset of GitHub, was eventually <strong><a href="https://github.com/blog/968-say-hello-to-hubot">open-sourced</a></strong> in late 2011.</p>
<blockquote>
<p>For the past year or so we've been telling people about Hubot [...] So <strong>we decided to rewrite him from scratch, open source him, and share him with everyone</strong>.</p>
</blockquote>
<p>Currently, the Windows Github client is not an open source software... but who knows, it <em>might</em> be open-sourced one day.</p> |
11,077,236 | Transparent window layer that is click-through and always stays on top | <p>This is some code that I picked up which I tried to implement. Its purpose is to create a form layer which is transparent, full screen, borderless, clickthrough, and always on top of other windows. It then lets you draw using directx over the top of it remaining otherwise transparent. </p>
<p>The parts that don't work are the click-through part, and the directx render. When I run it I basically have an invisible force field in front of all other windows and have to alt-tab around to visual studio to quickly press ALT F5 and end the debug (so at least the always on top and transparency works). I have been trying to figure out why those parts don't work, but my newbie c# skills fail me. hopefully someone can spot why and provide a modification.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Globalization;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using System.Threading;
namespace MinimapSpy
{
public partial class Form1 : Form
{
private Margins marg;
//this is used to specify the boundaries of the transparent area
internal struct Margins
{
public int Left, Right, Top, Bottom;
}
[DllImport("user32.dll", SetLastError = true)]
private static extern UInt32 GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
[DllImport("user32.dll")]
static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
public const int GWL_EXSTYLE = -20;
public const int WS_EX_LAYERED = 0x80000;
public const int WS_EX_TRANSPARENT = 0x20;
public const int LWA_ALPHA = 0x2;
public const int LWA_COLORKEY = 0x1;
[DllImport("dwmapi.dll")]
static extern void DwmExtendFrameIntoClientArea(IntPtr hWnd, ref Margins pMargins);
private Device device = null;
public Form1()
{
//Make the window's border completely transparant
SetWindowLong(this.Handle, GWL_EXSTYLE,
(IntPtr)(GetWindowLong(this.Handle, GWL_EXSTYLE) ^ WS_EX_LAYERED ^ WS_EX_TRANSPARENT));
//Set the Alpha on the Whole Window to 255 (solid)
SetLayeredWindowAttributes(this.Handle, 0, 255, LWA_ALPHA);
//Init DirectX
//This initializes the DirectX device. It needs to be done once.
//The alpha channel in the backbuffer is critical.
PresentParameters presentParameters = new PresentParameters();
presentParameters.Windowed = true;
presentParameters.SwapEffect = SwapEffect.Discard;
presentParameters.BackBufferFormat = Format.A8R8G8B8;
this.device = new Device(0, DeviceType.Hardware, this.Handle,
CreateFlags.HardwareVertexProcessing, presentParameters);
Thread dx = new Thread(new ThreadStart(this.dxThread));
dx.IsBackground = true;
dx.Start();
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs e)
{
//Create a margin (the whole form)
marg.Left = 0;
marg.Top = 0;
marg.Right = this.Width;
marg.Bottom = this.Height;
//Expand the Aero Glass Effect Border to the WHOLE form.
// since we have already had the border invisible we now
// have a completely invisible window - apart from the DirectX
// renders NOT in black.
DwmExtendFrameIntoClientArea(this.Handle, ref marg);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void dxThread()
{
while (true)
{
//Place your update logic here
device.Clear(ClearFlags.Target, Color.FromArgb(0, 0, 0, 0), 1.0f, 0);
device.RenderState.ZBufferEnable = false;
device.RenderState.Lighting = false;
device.RenderState.CullMode = Cull.None;
device.Transform.Projection = Matrix.OrthoOffCenterLH(0, this.Width, this.Height, 0, 0, 1);
device.BeginScene();
//Place your rendering logic here
device.EndScene();
//device.Present();
}
this.device.Dispose();
Application.Exit();
}
}
</code></pre> | 11,152,658 | 4 | 10 | null | 2012-06-18 05:14:04.403 UTC | 19 | 2021-05-19 06:13:29 UTC | 2012-07-10 17:06:51.967 UTC | null | 13,302 | null | 1,166,981 | null | 1 | 35 | c#|.net|winforms | 25,996 | <p>Here's a refined full sample code for making a window topmost - click through - transparent (= alpha blended). The sample makes a rotating color wheel which is rendered with DirectX, or actually with XNA 4.0, because I believe Microsoft has discontinued developing the managed directx and favours XNA today.</p>
<pre><code>using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.Xna.Framework.Graphics;
namespace ClickThroughXNA
{
public partial class Form1 : Form
{
// Directx graphics device
GraphicsDevice dev = null;
BasicEffect effect = null;
// Wheel vertexes
VertexPositionColor[] v = new VertexPositionColor[100];
// Wheel rotation
float rot = 0;
public Form1()
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
Size = new System.Drawing.Size(500, 500);
FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; // no borders
TopMost = true; // make the form always on top
Visible = true; // Important! if this isn't set, then the form is not shown at all
// Set the form click-through
int initialStyle = GetWindowLong(this.Handle, -20);
SetWindowLong(this.Handle, -20, initialStyle | 0x80000 | 0x20);
// Create device presentation parameters
PresentationParameters p = new PresentationParameters();
p.IsFullScreen = false;
p.DeviceWindowHandle = this.Handle;
p.BackBufferFormat = SurfaceFormat.Vector4;
p.PresentationInterval = PresentInterval.One;
// Create XNA graphics device
dev = new GraphicsDevice(GraphicsAdapter.DefaultAdapter, GraphicsProfile.Reach, p);
// Init basic effect
effect = new BasicEffect(dev);
// Extend aero glass style on form init
OnResize(null);
}
protected override void OnResize(EventArgs e)
{
int[] margins = new int[] { 0, 0, Width, Height };
// Extend aero glass style to whole form
DwmExtendFrameIntoClientArea(this.Handle, ref margins);
}
protected override void OnPaintBackground(PaintEventArgs e)
{
// do nothing here to stop window normal background painting
}
protected override void OnPaint(PaintEventArgs e)
{
// Clear device with fully transparent black
dev.Clear(new Microsoft.Xna.Framework.Color(0, 0, 0, 0.0f));
// Rotate wheel a bit
rot+=0.1f;
// Make the wheel vertexes and colors for vertexes
for (int i = 0; i < v.Length; i++)
{
if (i % 3 == 1)
v[i].Position = new Microsoft.Xna.Framework.Vector3((float)Math.Sin((i + rot) * (Math.PI * 2f / (float)v.Length)), (float)Math.Cos((i + rot) * (Math.PI * 2f / (float)v.Length)), 0);
else if (i % 3 == 2)
v[i].Position = new Microsoft.Xna.Framework.Vector3((float)Math.Sin((i + 2 + rot) * (Math.PI * 2f / (float)v.Length)), (float)Math.Cos((i + 2 + rot) * (Math.PI * 2f / (float)v.Length)), 0);
v[i].Color = new Microsoft.Xna.Framework.Color(1 - (i / (float)v.Length), i / (float)v.Length, 0, i / (float)v.Length);
}
// Enable position colored vertex rendering
effect.VertexColorEnabled = true;
foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply();
// Draw the primitives (the wheel)
dev.DrawUserPrimitives(PrimitiveType.TriangleList, v, 0, v.Length / 3, VertexPositionColor.VertexDeclaration);
// Present the device contents into form
dev.Present();
// Redraw immediatily
Invalidate();
}
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("dwmapi.dll")]
static extern void DwmExtendFrameIntoClientArea(IntPtr hWnd, ref int[] pMargins);
}
}
</code></pre> |
11,415,469 | Setup std::vector in class constructor | <p>I'm designing a class that has a <code>std::vector<int></code> as an instance variable. I'm using a <code>std::vector</code> because I need to set its size at runtime. Here are the relevant portions of my code: </p>
<pre><code>my_class.h:
#include <vector>
using std::vector;
class MyClass {
int size;
vector<int> vec;
}
my_class.cc:
#include "my_class.h"
using std::vector
MyClass::MyClass(int m_size) : size(m_size) {
vec = new vector<int>(size,0);
}
</code></pre>
<p>When I attempt to compile I get these error messages:</p>
<pre><code>g++ -c -Wall my_class.cc -o my_class.o
my_class.cc: In constructor ‘MyClass::MyClass(int):
my_class.cc:4 error: no match for ‘operator=’ in ‘((MyClass*)this)->My_Class::vec = ((*(const allocator_type*)(& std::allocator<int>())), (operator new(24u), (<statement>, ((std::vector<int>*)<anonymous>))))’
make: *** [my_class.o] Error 1
</code></pre>
<p>However, when I change the offending line to:</p>
<pre><code>vector<int> temp(size,0);
vec = temp;
</code></pre>
<p>It now compiles without a hitch and I get the desired behavior and can access my vector as </p>
<pre><code>vec[i] // i having been defined as an int yada yada yada
</code></pre>
<p>This workaround is okay, but I would like to understand why it works and the first method fails. Thanks in advance.</p> | 11,415,495 | 3 | 4 | null | 2012-07-10 14:24:53.503 UTC | 16 | 2020-08-16 08:00:01.8 UTC | 2017-06-14 23:52:02.883 UTC | null | 3,697,757 | null | 1,269,950 | null | 1 | 38 | c++|constructor|new-operator|stdvector | 114,197 | <p>Just do:</p>
<pre><code>MyClass::MyClass(int m_size) : size(m_size), vec(m_size, 0)
</code></pre>
<p>You already seem to know about initializer lists, why not initialize vector there directly? </p>
<pre><code>vec = new vector<int>(size,0);
</code></pre>
<p>is illegal because <code>new</code> returns a pointer and in your case <code>vec</code> is an object.</p>
<p>Your second option:</p>
<pre><code>vector<int> temp(size,0);
vec = temp;
</code></pre>
<p>although it compiles, does extra work for no gain. By the time you reach the assignment, two vectors would already have been constructed and discarded afterwards.</p> |
11,088,483 | SoapUI "failed to load url" error when loading WSDL | <p>I keep having some weird problems. The main one is that I keep getting the following error when trying to add a WSDL to a new project:</p>
<pre><code>Error loading [https://.../token?wsdl]: java.lang.Exception: Failed to load url; https://.../token?wsdl, 0 -
</code></pre>
<p>Here's the message recorded in the error.log file:</p>
<pre><code>java.lang.Exception: Failed to load url; https://.../token?wsdl, 0 -
at com.eviware.soapui.impl.wsdl.support.wsdl.UrlWsdlLoader.load(UrlWsdlLoader.java:184)
at com.eviware.soapui.impl.wsdl.support.wsdl.WsdlLoader.loadXmlObject(WsdlLoader.java:121)
at com.eviware.soapui.impl.wsdl.support.xsd.SchemaUtils.getDefinitionParts(SchemaUtils.java:535)
at com.eviware.soapui.impl.wsdl.support.xsd.SchemaUtils.getDefinitionParts(SchemaUtils.java:524)
at com.eviware.soapui.impl.support.definition.support.AbstractDefinitionCache.update(AbstractDefinitionCache.java:97)
at com.eviware.soapui.impl.support.definition.support.AbstractDefinitionContext$Loader.construct(AbstractDefinitionContext.java:226)
at com.eviware.soapui.support.swing.SwingWorkerDelegator.construct(SwingWorkerDelegator.java:46)
at com.eviware.soapui.support.swing.SwingWorker$2.run(SwingWorker.java:149)
at java.lang.Thread.run(Unknown Source)
</code></pre>
<p>I verified that the application at that URL is up and running, and I can get to the WSDL from a web browser, but I keep getting this error message no matter what. I am using SoapUI 4.5.0 (32-bit) on a Windows 7 box. I've also tried the 64-bit version with the same results. It happens whether I am on VPN or not. </p>
<p>Do you know why I might be getting this error?</p> | 11,092,004 | 16 | 0 | null | 2012-06-18 18:04:47.033 UTC | 7 | 2022-09-04 10:03:59.79 UTC | 2017-09-12 19:56:09.267 UTC | null | 3,474,146 | null | 875,440 | null | 1 | 38 | java|web-services|xsd|wsdl|soapui | 203,032 | <p>I have had similar problems and worked around them by saving the WSDL locally. Don't forget to save any XSD files as well. You may need to edit the WSDL to specify an appropriate location for XSDs.</p> |
11,127,109 | Emacs 24 Package System Initialization Problems | <p>It seems to me that the new Package system that is built-in on Emacs 24 has some flaws when it comes to properly loading and initializing the installed packages. </p>
<p>Recently, I upgraded to Emacs 24.1.1 which was realeased on 6/10/2012 and I have been trying to use the built-in package system and have installed several packages using it, but they all have a similar problem related to autoload and initialization. </p>
<p>For example, I use a package called <code>smex</code> which provides enhancements for using the <code>M-x</code> chord. It requires you to define a key for <code>M-x</code>, so I added <code>(global-set-key (kbd "M-x") 'smex)</code> in my <code>init.el</code> file. But after starting emacs I press the <code>M-x</code> chord and I get the message <em>"Symbol's function definition is void: smex"</em> ... If I also put <code>(require 'smex)</code> in my init.el file I get the error message <em>"File error: Cannot open load file, smex"</em> </p>
<p>Adding the location of smex to the load-path variable makes it work as expected, however, that seems to defeat the whole purpose of having a package system in the first place... </p>
<p>Any thoughts? Is there a better way or do we live with this limitation for now?</p> | 11,140,619 | 2 | 0 | null | 2012-06-20 19:49:52.8 UTC | 23 | 2013-10-20 22:23:39.52 UTC | 2012-06-20 20:26:28.103 UTC | null | 11,507 | null | 11,507 | null | 1 | 45 | emacs|dot-emacs|emacs24 | 14,366 | <p>The packages that you install with <code>package.el</code> are activated by default <strong>after</strong> your <code>.emacs</code> is loaded.
To be able to use them before the end of your <code>.emacs</code> you need to activate them by using the commands:</p>
<pre class="lang-el prettyprint-override"><code>(setq package-enable-at-startup nil)
(package-initialize)
</code></pre> |
11,222,440 | How to create a reference to a variable in python? | <p>In the code:</p>
<pre><code>y = 7
x = y
x = 8
</code></pre>
<p>Now, <code>y</code> will be 7 and x will be 8. But actually I wan to change <code>y</code>. Can I assign the reference of <code>y</code> and do that?</p>
<p>For example, in C++ the same thing can be achieved as:</p>
<pre class="lang-c++ prettyprint-override"><code>int y = 8;
int &x = y;
x = 9;
</code></pre>
<p>Now both <code>y</code> & <code>x</code> will be 9</p> | 11,222,835 | 4 | 0 | null | 2012-06-27 08:43:03.303 UTC | 28 | 2021-09-24 03:49:02.76 UTC | 2021-07-02 16:57:16.64 UTC | null | 1,035,789 | null | 1,035,789 | null | 1 | 61 | python|reference | 79,060 | <p>No, you cannot. As other answer point out, you can (ab?)use aliasing of mutable objects to achieve a similar effect. However, that's not the same thing as C++ references, and I want to explain what actually happens to avoid any misconceptions.</p>
<p>You see, in C++ (and other languages), a variable (and object fields, and entries in collections, etc.) is a storage location and you write a value (for instance, an integer, an object, or a pointer) to that location. In this model, references are an alias for a storage location (of any kind) - when you assign to a non-reference variable, you copy a value (even if it's just a pointer, it's still a value) to the storage location; when you assign to a reference, you copy to a storage location somewhere else. Note that you cannot change a reference itself - once it is bound (and it has to as soon as you create one) all assignments to it alter not the reference but whatever is referred to.</p>
<p>In Python (and other languages), a variable (and object fields, and entries in collections, etc.) is a just a name. Values are <em>somewhere</em> else (e.g. sprinkled all over the heap), and a variable refers (not in the sense of C++ references, more like a pointer minus the pointer arithmetic) to a value. Multiple names can refer to the same value (which is generally a good thing). Python (and other languages) calls whatever is needed to refer to a value a reference, despite being pretty unrelated to things like C++ references and pass-by-reference. Assigning to a variable (or object field, or ...) simply makes it refer to another value. The whole model of storage locations does not apply to Python, the programmer never handles storage locations for values. All he stores and shuffles around are Python references, and those are not values in Python, so they cannot be target of other Python references.</p>
<p>All of this is independent of mutability of the value - it's the same for ints and lists, for instance. You cannot take a variable that refers to either, and overwrite the object it points to. You can only tell the object to modify parts of itself - say, change some reference it contains.</p>
<p>Is this a more restrictive model? Perhaps, but it's powerful enough most of the time. And when it isn't you can work around it, either with a custom class like the one given below, or (equivalent, but less obvious) a single-element collection.</p>
<pre><code>class Reference:
def __init__(self, val):
self._value = val # just refers to val, no copy
def get(self):
return self._value
def set(self, val):
self._value = val
</code></pre>
<p>That still won't allow you to alias a "regular" variable or object field, but you can have multiple variables referring to the same <code>Reference</code> object (ditto for the mutable-singleton-collection alternative). You just have to be careful to always use <code>.get()</code>/<code>.set()</code> (or <code>[0]</code>).</p> |
12,725,322 | Alter folder permission in windows command line? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/2928738/how-to-grant-permission-to-users-for-a-directory-using-command-line-in-windows">How to grant permission to users for a directory using command line in Windows?</a> </p>
</blockquote>
<p>I want to grant all users of a system the permissions of read, write and modify for a folder.
I think there would be a command line that I use to do that, but if there is nothing and I have to write a code for it please help me with it.</p>
<p>Main Problem is that I want to grant these permissions to all users, usually I don't care about UserNames and I want to put "*" instead of usernames, to apply new permissions for all users.</p>
<p>any idea?
Thanks.</p> | 12,725,569 | 1 | 3 | null | 2012-10-04 10:31:06.05 UTC | 5 | 2012-10-04 11:00:31.153 UTC | 2017-05-23 12:13:44.067 UTC | null | -1 | null | 1,635,051 | null | 1 | 7 | windows|cmd | 80,448 | <p>There <strong>is</strong> a command line - <a href="http://technet.microsoft.com/en-us/library/bb490872.aspx" rel="noreferrer">CACLS</a>.</p>
<p>For example, to add "Everyone" with "Full Control" to the folder <code>c:\temp\test</code> you would use:</p>
<pre><code>REM /t means "apply change recursively"
REM /e means "edit existing DACL".
REM Omitting this will overwrite the existing DACL.
cacls c:\temp\Test /t /e /g Everyone:f
</code></pre> |
12,712,149 | Haskell parser to AST data type, assignment | <p>I have been searching around the interwebs for a couple of days, trying to get an answer to my questions and i'm finally admitting defeat.<br>
I have been given a grammar:</p>
<p><code>Dig ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9<br>
Int ::= Dig | Dig Int<br>
Var ::= a | b | ... z | A | B | C | ... | Z<br>
Expr ::= Int | - Expr | + Expr Expr | * Expr Expr | Var | let Var = Expr in Expr</code> </p>
<p>And i have been told to parse, evaluate and print expressions using this grammar<br>
where the operators <code>* + -</code> has their normal meaning<br>
The specific task is to write a function <code>parse :: String -> AST</code> </p>
<p>that takes a string as input and returns an abstract syntax tree when the input is in the correct format (which i can asume it is). </p>
<p>I am told that i might need a suitable data type and that data type might need to derive from some other classes. </p>
<p>Following an example output<br>
<code>data AST = Leaf Int | Sum AST AST | Min AST | ...</code> </p>
<p>Further more, i should consider writing a function<br>
<code>tokens::String -> [String]</code><br>
to split the input string into a list of tokens<br>
Parsing should be accomplished with<br>
<code>ast::[String] -> (AST,[String])</code><br>
where the input is a list of tokens and it outputs an AST, and to parse sub-expressions i should simply use the ast function recursively.</p>
<p>I should also make a printExpr method to print the result so that<br>
<code>printE: AST -> String</code><br>
<code>printE(parse "* 5 5")</code> yields either <code>"5*5"</code> or <code>"(5*5)"</code><br>
and also a function to evaluate the expression<br>
<code>evali :: AST -> Int</code></p>
<p>I would just like to be pointed in the right direction of where i might start. I have little knowledge of Haskell and FP in general and trying to solve this task i made some string handling function out of Java which made me realize that i'm way off track.<br>
So a little pointer in the right direction, and maybe an explantion to 'how' the AST should look like<br>
Third day in a row and still no running code, i really appreciate any attempt to help me find a solution!
Thanks in advance!<br>
<strong>Edit</strong> </p>
<p>I might have been unclear:
I'm wondering how i should go about from having read and tokenized an input string to making an AST.</p> | 12,719,509 | 3 | 2 | null | 2012-10-03 15:49:25.68 UTC | 10 | 2014-08-02 21:08:14.383 UTC | 2012-10-03 21:19:03.543 UTC | null | 1,717,572 | null | 1,717,572 | null | 1 | 8 | parsing|haskell|abstract-syntax-tree | 12,282 | <h1>Parsing tokens into an Abstract Syntax Tree</h1>
<p>OK, let's take your grammar</p>
<pre><code>Dig ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
Int ::= Dig | Dig Int
Var ::= a | b | ... z | A | B | C | ... | Z
Expr ::= Int | - Expr | + Expr Expr | * Expr Expr | Var | let Var = Expr in Expr
</code></pre>
<p>This is a nice easy grammar, because you can tell from the first token what sort of epression it will be.
(If there was something more complicated, like <code>+</code> coming between numbers, or <code>-</code> being used for subtraction as
well as negation, you'd need the list-of-successes trick, explained in
<a href="http://roman-dushkin.narod.ru/files/fp__jeroen_fokker_001.pdf" rel="noreferrer">Functional Parsers</a>.)</p>
<p>Let's have some sample raw input:</p>
<pre><code>rawinput = "- 6 + 45 let x = - 5 in * x x"
</code></pre>
<p>Which I understand from the grammar represents <code>"(- 6 (+ 45 (let x=-5 in (* x x))))"</code>,
and I'll assume you tokenised it as</p>
<pre><code>tokenised_input' = ["-","6","+","4","5","let","x","=","-","5","in","*","x","x"]
</code></pre>
<p>which fits the grammar, but you might well have got</p>
<pre><code>tokenised_input = ["-","6","+","45","let","x","=","-","5","in","*","x","x"]
</code></pre>
<p>which fits your sample <code>AST</code> better. I think it's good practice to name your AST after bits of your grammar,
so I'm going to go ahead and replace</p>
<pre><code>data AST = Leaf Int | Sum AST AST | Min AST | ...
</code></pre>
<p>with </p>
<pre><code>data Expr = E_Int Int | E_Neg Expr | E_Sum Expr Expr | E_Prod Expr Expr | E_Var Char
| E_Let {letvar::Char,letequal:: Expr,letin::Expr}
deriving Show
</code></pre>
<p>I've named the bits of an <code>E_Let</code> to make it clearer what they represent.</p>
<h2>Writing a parsing function</h2>
<p>You could use <code>isDigit</code> by adding <code>import Data.Char (isDigit)</code> to help out:</p>
<pre><code>expr :: [String] -> (Expr,[String])
expr [] = error "unexpected end of input"
expr (s:ss) | all isDigit s = (E_Int (read s),ss)
| s == "-" = let (e,ss') = expr ss in (E_Neg e,ss')
| s == "+" = (E_Sum e e',ss'') where
(e,ss') = expr ss
(e',ss'') = expr ss'
-- more cases
</code></pre>
<p>Yikes! Too many let clauses obscuring the meaning,
and we'll be writing the same code for <code>E_Prod</code> and very much worse for <code>E_Let</code>.
Let's get this sorted out! </p>
<p>The standard way of dealing with this is to write some combinators;
instead of tiresomely threading the input <code>[String]</code>s through our definition, define ways to
mess with the output of parsers (map) and combine
multiple parsers into one (lift).</p>
<h2>Clean up the code 1: map</h2>
<p>First we should define <code>pmap</code>, our own equivalent of the <code>map</code> function so we can do <code>pmap E_Neg (expr1 ss)</code>
instead of <code>let (e,ss') = expr1 ss in (E_Neg e,ss')</code></p>
<pre><code>pmap :: (a -> b) -> ([String] -> (a,[String])) -> ([String] -> (b,[String]))
</code></pre>
<p>nonono, I can't even read that! We need a type synonym:</p>
<pre><code>type Parser a = [String] -> (a,[String])
pmap :: (a -> b) -> Parser a -> Parser b
pmap f p = \ss -> let (a,ss') = p ss
in (f a,ss')
</code></pre>
<p>But really this would be better if I did</p>
<pre><code>data Parser a = Par [String] -> (a,[String])
</code></pre>
<p>so I could do</p>
<pre><code>instance Functor Parser where
fmap f (Par p) = Par (pmap f p)
</code></pre>
<p>I'll leave that for you to figure out if you fancy.</p>
<h2>Clean up the code 2: combining two parsers</h2>
<p>We also need to deal with the situation when we have two parsers to run,
and we want to combine their results using a function. This is called lifting the function to parsers.</p>
<pre><code>liftP2 :: (a -> b -> c) -> Parser a -> Parser b -> Parser c
liftP2 f p1 p2 = \ss0 -> let
(a,ss1) = p1 ss0
(b,ss2) = p2 ss1
in (f a b,ss2)
</code></pre>
<p>or maybe even three parsers:</p>
<pre><code>liftP3 :: (a -> b -> c -> d) -> Parser a -> Parser b -> Parser c -> Parser d
</code></pre>
<p>I'll let you think how to do that.
In the let statement you'll need <code>liftP5</code> to parse the sections of a let statement,
lifting a function that ignores the <code>"="</code> and <code>"in"</code>. You could make</p>
<pre><code>equals_ :: Parser ()
equals_ [] = error "equals_: expected = but got end of input"
equals_ ("=":ss) = ((),ss)
equals_ (s:ss) = error $ "equals_: expected = but got "++s
</code></pre>
<p>and a couple more to help out with this.</p>
<p>Actually, <code>pmap</code> could also be called <code>liftP1</code>, but map is the traditional name for that sort of thing.</p>
<h2>Rewritten with the nice combinators</h2>
<p>Now we're ready to clean up <code>expr</code>:</p>
<pre><code>expr :: [String] -> (Expr,[String])
expr [] = error "unexpected end of input"
expr (s:ss) | all isDigit s = (E_Int (read s),ss)
| s == "-" = pmap E_Neg expr ss
| s == "+" = liftP2 E_Sum expr expr ss
-- more cases
</code></pre>
<p>That'd all work fine. Really, it's OK. But <code>liftP5</code> is going to be a bit long, and feels messy. </p>
<h2>Taking the cleanup further - the ultra-nice Applicative way</h2>
<p>Applicative Functors is the way to go.
Remember I suggested refactoring as</p>
<pre><code>data Parser a = Par [String] -> (a,[String])
</code></pre>
<p>so you could make it an instance of <code>Functor</code>? Perhaps you don't want to,
because all you've gained is a new name <code>fmap</code> for the perfectly working <code>pmap</code> and
you have to deal with all those <code>Par</code> constructors cluttering up your code.
Perhaps this will make you reconsider, though; we can <code>import Control.Applicative</code>,
then using the <code>data</code> declaration, we can
define <code><*></code>, which sort-of means <code>then</code> and use <code><$></code> instead of <code>pmap</code>, with <code>*></code> meaning
<code><*>-but-forget-the-result-of-the-left-hand-side</code> so you would write</p>
<pre><code>expr (s:ss) | s == "let" = E_Let <$> var *> equals_ <*> expr <*> in_ *> expr
</code></pre>
<p>Which looks a lot like your grammar definition, so it's easy to write code that works first time.
This is how I like to write Parsers. In fact, it's how I like to write an awful lot of things.
You'd only have to define <code>fmap</code>, <code><*></code> and <code>pure</code>, all simple ones, and no long repetative <code>liftP3</code>, <code>liftP4</code> etc.</p>
<p>Read up about Applicative Functors. They're great.</p>
<ul>
<li><a href="http://learnyouahaskell.com/functors-applicative-functors-and-monoids" rel="noreferrer">Applicative in Learn You a Haskell for Great Good!</a></li>
<li><a href="http://en.wikibooks.org/wiki/Haskell/Applicative_Functors" rel="noreferrer">Applicative in Haskell wikibook</a></li>
</ul>
<p>Hints for making Parser applicative: <code>pure</code> doesn't change the list.
<code><*></code> is like <code>liftP2</code>, but the function doesn't come from outside, it comes as the output from <code>p1</code>.</p> |
12,928,103 | SDWebImage process images before caching | <p>I fetch a lot of images from the web, and they are all kind of sizes - they can be big, small etc..</p>
<p>So I can resize them when I display them in the cell but this is inefficient. It's way better to resize them after SDWebImage have download them and cache them resized, instead of storing large images on disk and resize them for every cell.</p>
<p>So how can I do this with SDWebImage, or I have to hack a bit onto the class?</p> | 12,929,138 | 4 | 0 | null | 2012-10-17 06:05:01.047 UTC | 11 | 2017-02-08 22:58:26.82 UTC | null | null | null | null | 1,190,518 | null | 1 | 9 | iphone|ios|cocoa-touch|sdwebimage | 7,232 | <p>I had the same problem as you, and tried tweaking SDWebImage first, but ended up building my own component that solved the problem. You can take take a look at it here : <a href="https://github.com/adig/RemoteImageView" rel="noreferrer">https://github.com/adig/RemoteImageView</a></p> |
12,831,524 | Can dcast be used without an aggregate function? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/12829995/this-r-reshaping-should-be-simple-but">This R reshaping should be simple, but</a> </p>
</blockquote>
<p><code>dcast</code> from <code>reshape2</code> works without a formula where there are no duplicates. Take these example data:</p>
<pre><code>df <- structure(list(id = c("A", "B", "C", "A", "B", "C"), cat = c("SS",
"SS", "SS", "SV", "SV", "SV"), val = c(220L, 222L, 223L, 224L,
225L, 2206L)), .Names = c("id", "cat", "val"), class = "data.frame", row.names = c(NA,
-6L))
</code></pre>
<p>I'd like to <code>dcast</code> these data and just have the values tabulated, without applying any function to the <code>value.var</code> including the default <code>length</code>.</p>
<p>In this case, it works fine.</p>
<pre><code>> dcast(df, id~cat, value.var="val")
id SS SV
1 A 220 224
2 B 222 225
3 C 223 2206
</code></pre>
<p>But when there are duplicate variables, the <code>fun</code> defaults to <code>length</code>. Is there a way to avoid it?</p>
<pre><code>df2 <- structure(list(id = c("A", "B", "C", "A", "B", "C", "C"), cat = c("SS",
"SS", "SS", "SV", "SV", "SV", "SV"), val = c(220L, 222L, 223L,
224L, 225L, 220L, 1L)), .Names = c("id", "cat", "val"), class = "data.frame", row.names = c(NA,
-7L))
> dcast(df2, id~cat, value.var="val")
Aggregation function missing: defaulting to length
id SS SV
1 A 1 1
2 B 1 1
3 C 1 2
</code></pre>
<p>Ideally what I'm looking for is to add a <code>fun = NA</code>, as in don't try to aggregate the <code>value.var</code>. The result I'd like when dcasting df2:</p>
<pre><code> id SS SV
1 A 220 224
2 B 222 225
3 C 223 220
4. C NA 1
</code></pre> | 12,831,856 | 2 | 4 | null | 2012-10-11 03:00:18.65 UTC | 9 | 2012-10-11 03:45:09.66 UTC | 2017-05-23 12:32:15.637 UTC | null | -1 | null | 313,163 | null | 1 | 26 | r|reshape2 | 25,826 | <p>I don't think there is a way to do it directly but we can add in an additional column which will help us out</p>
<pre><code>df2 <- structure(list(id = c("A", "B", "C", "A", "B", "C", "C"), cat = c("SS",
"SS", "SS", "SV", "SV", "SV", "SV"), val = c(220L, 222L, 223L,
224L, 225L, 220L, 1L)), .Names = c("id", "cat", "val"), class = "data.frame", row.names = c(NA,
-7L))
library(reshape2)
library(plyr)
# Add a variable for how many times the id*cat combination has occured
tmp <- ddply(df2, .(id, cat), transform, newid = paste(id, seq_along(cat)))
# Aggregate using this newid and toss in the id so we don't lose it
out <- dcast(tmp, id + newid ~ cat, value.var = "val")
# Remove newid if we want
out <- out[,-which(colnames(out) == "newid")]
> out
# id SS SV
#1 A 220 224
#2 B 222 225
#3 C 223 220
#4 C NA 1
</code></pre> |
13,017,097 | Exclude individual test from 'before' method in JUnit | <p>All tests in my test class execute a 'before' method (annotated with JUnit's <code>@Before</code>) before the execution of each test.</p>
<p>I need a particular test not to execute this before method.</p>
<p>Is there a way to do it?</p> | 13,017,223 | 8 | 0 | null | 2012-10-22 18:05:33.067 UTC | 3 | 2021-11-29 12:51:03.75 UTC | 2012-10-22 18:15:36.54 UTC | null | 597,548 | null | 1,401,475 | null | 1 | 28 | java|testing|junit | 30,937 | <p>Unfortunately you have to code this logic. JUnit does not have such feature.
Generally you have 2 solutions:</p>
<ol>
<li>Just separate test case to 2 test cases: one that contains tests that require "before" running and second that contains tests that do not require this.</li>
<li>Implement your own test running and annotate your test to use it. Create your own annotation <code>@RequiresBefore</code> and mark tests that need this with this annotation. The test runner will parse the annotation and decide whether to run "before" method or not.</li>
</ol>
<p>The second solution is clearer. The first is simpler. This is up to you to chose one of them.</p> |
12,848,712 | Changed project name in Xcode causing naming error | <p>My old name consisted of a camel case type name similar to this</p>
<p><strong>MyApp</strong></p>
<p>I then changed it to </p>
<p><strong>Myapp</strong> 'notice the A is now non-caps'</p>
<p>I changed this by clicking <code>MyApp</code> name in the navigator menu and changing it, up came a help box asking me to do system wide changes I clicked YES!</p>
<p>but now when I build this application its saying the name of my app is:</p>
<p><strong>Myapp-temp-caseinsensitive-rename</strong></p>
<p>I am now wondering how do I get rid of the -temp-caseinsensitive-rename portion?</p> | 12,848,841 | 6 | 1 | null | 2012-10-11 21:23:09.467 UTC | 13 | 2019-08-24 12:06:02.343 UTC | 2013-02-13 23:25:58.563 UTC | null | 1,730,272 | null | 748,343 | null | 1 | 32 | ios|xcode|xcode4|xcode4.5|xcode4.6 | 20,206 | <p>Check the product name in build settings and make sure everywhere it is Myapp. If that is done, </p>
<ul>
<li>Close your project -> go to finder.</li>
<li>Right click on your .xcodeproject file and click on show package
contents.</li>
<li>Then right click on your project.pbxproj and open it in some text
editor.</li>
<li>Then search for Myapp-temp-caseinsensitive-rename and manually rename
it.</li>
<li>Save it after changing and then reopen the project.</li>
</ul>
<p>Make sure you have taken a back up of your project before doing this.</p> |
12,986,996 | Conditional for in Python | <p>Does Python have something like below?</p>
<pre><code>for item in items #where item>3:
#.....
</code></pre>
<p>I mean Python 2.7 and Python 3.3 both together.</p> | 12,987,032 | 5 | 0 | null | 2012-10-20 09:16:28.06 UTC | 5 | 2018-08-31 21:46:06.893 UTC | null | null | null | null | 1,708,058 | null | 1 | 39 | python | 51,878 | <p>You can combine the loop with a <a href="http://docs.python.org/reference/expressions.html#grammar-token-generator_expression" rel="noreferrer">generator expression</a>:</p>
<pre><code>for x in (y for y in items if y > 10):
....
</code></pre>
<p><a href="http://docs.python.org/2/library/itertools.html#itertools.ifilter" rel="noreferrer"><code>itertools.ifilter</code></a> (py2) / <a href="https://docs.python.org/3/library/functions.html#filter" rel="noreferrer"><code>filter</code></a> (py3) is another option:</p>
<pre><code>items = [1,2,3,4,5,6,7,8]
odd = lambda x: x % 2 > 0
for x in filter(odd, items):
print(x)
</code></pre> |
17,080,416 | Configure output cache per user mvc | <p>I have a user specific dashboard. The dashboard will only change daily, I want to use <code>MVC's</code> <code>OutputCache</code>. Is there any way to configure the caching per user and to expire when the request is a new day?</p>
<p>I have researched this and found you can extend the <code>OutputCache</code> attribute to dynamically set your duration however how can I configure this per user?</p>
<p>Thanks in advance</p> | 17,081,534 | 2 | 0 | null | 2013-06-13 06:18:11.04 UTC | 13 | 2014-08-06 17:03:32.563 UTC | 2013-12-30 21:29:07.96 UTC | null | 727,208 | null | 1,401,320 | null | 1 | 18 | c#|asp.net-mvc|asp.net-mvc-3 | 4,671 | <p>In your <code>Web.config</code>:</p>
<pre><code><caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="Dashboard" duration="86400" varyByParam="*" varyByCustom="User" location="Server" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</code></pre>
<p>In your <code>Controller</code>/<code>Action</code>:</p>
<pre><code>[OutputCache(CacheProfile="Dashboard")]
public class DashboardController { ...}
</code></pre>
<p>Then in your <code>Global.asax</code>:</p>
<pre><code>//string arg filled with the value of "varyByCustom" in your web.config
public override string GetVaryByCustomString(HttpContext context, string arg)
{
if (arg == "User")
{
// depends on your authentication mechanism
return "User=" + context.User.Identity.Name;
//return "User=" + context.Session.SessionID;
}
return base.GetVaryByCustomString(context, arg);
}
</code></pre>
<p>In essence, <code>GetVaryByCustomString</code> lets you write a custom method to determine whether there will be a Cache <code>hit/miss</code>.</p> |
25,786,778 | C++ Qt where's the std::unique_ptr Qt version? | <p>So when programming in Qt I like to go with the Qt implementation as far as possible.
As far as I've seen there's no Qt version of the <code>std::unique_ptr</code> or is there?</p>
<p>What would be the alternatives that produce the "same" result in Qt if it doesn't exist?</p> | 25,786,828 | 1 | 7 | null | 2014-09-11 11:53:28.333 UTC | 3 | 2014-09-11 11:56:49.387 UTC | null | null | null | null | 3,065,406 | null | 1 | 28 | c++|qt|qt5 | 20,240 | <p>The Qt equivalent to <code>std::unique_ptr</code> is <a href="http://qt-project.org/doc/qt-5/qscopedpointer.html" rel="noreferrer"><code>QScopedPointer</code></a>.</p>
<p>It's significantly less useful as it doesn't support move semantics, making it closer in utility to C++03 <a href="http://en.cppreference.com/w/cpp/memory/auto_ptr" rel="noreferrer"><code>std::auto_ptr</code></a> (<a href="https://stackoverflow.com/questions/3697686/what-is-the-problem-with-auto-ptr">Why is auto_ptr being deprecated?</a>).</p> |
58,014,360 | How do you use Basic Authentication with System.Net.Http.HttpClient? | <p>I'm trying to implement a rest client in c# .net core that needs to first do Basic Authentication, then leverage a Bearer token in subsequent requests. </p>
<p>When I try to do Basic Authentication in combination with client.PostAsync with a FormUrlEncodedContent object, I'm getting an exception: </p>
<pre><code>System.InvalidOperationException occurred in System.Net.Http.dll: 'Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.'
</code></pre>
<pre><code>//setup reusable http client
HttpClient client = new HttpClient();
Uri baseUri = new Uri(url);
client.BaseAddress = baseUri;
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.ConnectionClose = true;
//Post body content
var values = new List<KeyValuePair<string,string>>();
values.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
var content = new FormUrlEncodedContent(values);
//Basic Authentication
var authenticationString = $"{clientId}:{clientSecret}";
var base64EncodedAuthenticationString = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(authenticationString));
content.Headers.Add("Authorization", $"Basic {base64EncodedAuthenticationString}");
//make the request
var task = client.PostAsync("/oauth2/token",content);
var response = task.Result;
response.EnsureSuccessStatusCode();
string responseBody = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(responseBody);
</code></pre>
<pre><code>Exception has occurred: CLR/System.InvalidOperationException
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Net.Http.dll: 'Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.'
at System.Net.Http.Headers.HttpHeaders.GetHeaderDescriptor(String name)
at System.Net.Http.Headers.HttpHeaders.Add(String name, String value)
</code></pre> | 58,015,049 | 6 | 4 | null | 2019-09-19 15:25:01.62 UTC | 6 | 2022-03-25 10:45:11.953 UTC | 2019-09-19 15:51:05.49 UTC | null | 1,310 | null | 1,310 | null | 1 | 45 | c#|basic-authentication|dotnet-httpclient | 74,456 | <p>It looks like you can't use PostAsync and have access to mess with the Headers for authentication. I had to use an HttpRequestMessage and SendAsync.</p>
<pre><code>//setup reusable http client
HttpClient client = new HttpClient();
Uri baseUri = new Uri(url);
client.BaseAddress = baseUri;
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.ConnectionClose = true;
//Post body content
var values = new List<KeyValuePair<string, string>>();
values.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
var content = new FormUrlEncodedContent(values);
var authenticationString = $"{clientId}:{clientSecret}";
var base64EncodedAuthenticationString = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(authenticationString));
var requestMessage = new HttpRequestMessage(HttpMethod.Post, "/oauth2/token");
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic", base64EncodedAuthenticationString);
requestMessage.Content = content;
//make the request
var task = client.SendAsync(requestMessage);
var response = task.Result;
response.EnsureSuccessStatusCode();
string responseBody = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(responseBody);
</code></pre> |
9,646,088 | emacs interactive commands with default value | <p>I am wondering how is that some interactive commands in emacs present default value while others don't. For instance when I am in C file and cursor stands on <code>printf</code>, running <code>manual-entry</code> will suggest showing manual page for <code>printf</code> by default. I would like to make my own interactive commands with default value. How?
It seems like thing-at-point is a good direction, but how do I blend thing-at-point and interactive together?</p> | 9,646,268 | 1 | 0 | null | 2012-03-10 11:34:53.133 UTC | 1 | 2012-03-10 21:16:51.103 UTC | 2012-03-10 21:16:51.103 UTC | null | 789,593 | null | 502,421 | null | 1 | 28 | emacs|elisp|interactive | 5,165 | <p>You already have good starting points to research your own solution.</p>
<p><code>thing-at-point</code> is probably useful in this context. I recently <a href="https://stackoverflow.com/a/9620373/903943">answered</a>
a question where I explained how to solve this type of problem by exploring the
Emacs code base.</p>
<p>Here is a rough toy function I came up with.</p>
<pre class="lang-lisp prettyprint-override"><code>(defun say-word (word)
(interactive (list
(read-string (format "word (%s): " (thing-at-point 'word))
nil nil (thing-at-point 'word))))
(message "The word is %s" word))
</code></pre>
<p>One key thing here is to understand how the <code>interactive</code> form works. I would
read the relevant <a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/Using-Interactive.html" rel="noreferrer">manual section</a> carefully.</p> |
9,958,825 | How do I bind Twitter Bootstrap tooltips to dynamically created elements? | <p>I'm using Twitter bootstrap tooltips with javascript like the following:</p>
<pre><code>$('a[rel=tooltip]').tooltip();
</code></pre>
<p>My markup looks like this:</p>
<pre><code><a rel="tooltip" title="Not implemented" class="btn"><i class="icon-file"></i></a>
</code></pre>
<p>This works fine, but I add <code><a></code> elements dynamically and the tooltips aren't showing up for those dynamic elements. I know it's because I only bind .tooltip() once when the document is finished loaded with the typical jquery <code>$(document).ready(function()</code> functionality.</p>
<p>How can I bind this to dynamically created elements? Usually I would do this via the jquery live() method. However, what is the event that I use to bind? I'm just not sure how to hook up the bootstrap .tooltip() with jquery .live().</p>
<p>I've found one way to make this work is something like this:</p>
<pre><code>/* Add new 'rows' when plus sign is clicked */
$("a.add").live('click', function () {
var clicked_li = $(this).parent('li');
var clone = clicked_li.clone();
clone.find(':input').each(function() {
$(this).val('');
});
clicked_li.after(clone);
$('a[rel=tooltip]').tooltip();
});
</code></pre>
<p>This works, but seems kind of hackish. I'm also calling the exact same .tooltip() line in the $(ready) call. So, do the elements that exist when the page first loads and match that selector end up with the tooltip twice?</p>
<p>I don't see any problems with this approach. I'm just looking for a best practice or understanding of the behavior.</p> | 10,420,203 | 8 | 6 | null | 2012-03-31 19:08:00.307 UTC | 67 | 2020-11-19 20:34:03.733 UTC | 2012-04-01 02:47:53.987 UTC | null | 1,108,031 | null | 1,108,031 | null | 1 | 290 | jquery|twitter-bootstrap | 121,554 | <p>Try this one: </p>
<pre><code>$('body').tooltip({
selector: '[rel=tooltip]'
});
</code></pre> |
10,182,625 | Is there a shorthand for creating a String constant in Spring context XML file? | <p>I need to define a string value in Spring context XML file that is shared by multiple beans. </p>
<p>This is how I do it:</p>
<pre class="lang-xml prettyprint-override"><code><bean id="aSharedProperty" class="java.lang.String">
<constructor-arg type="java.lang.String" value="All beans need me :)"/>
</bean>
</code></pre>
<p>Creating a java.lang.String bean by passing a constructor argument of java.lang.String seems kludgy.</p>
<p>Is there a shortcut?</p>
<p>I know this property can be passed using PropertyOverrideConfigurer, but I want to keep this property within the XML file.</p> | 15,814,575 | 4 | 0 | null | 2012-04-16 22:30:27.787 UTC | 9 | 2014-06-12 08:35:20.01 UTC | 2014-06-12 08:35:20.01 UTC | null | 1,199,132 | null | 121,371 | null | 1 | 36 | java|spring | 26,868 | <p>A shorthand to the solution proposed by mrembisz goes like this:</p>
<pre class="lang-xml prettyprint-override"><code><context:property-placeholder properties-ref="myProperties"/>
<util:properties id="myProperties">
<prop key="aSharedProperty">All beans need me :)</prop>
</util:properties>
</code></pre> |
28,352,963 | Change Toolbar Menu Item color (non-hidden action) | <p>Say I have a menu (options_menu.xml) similar to the following:</p>
<pre><code><menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >
<item android:id="@+id/action_login"
android:title="Login"
app:showAsAction="always"/>
</menu>
</code></pre>
<p>which I inflate into the new Toolbar item</p>
<pre><code>mToolbar.inflateMenu(R.menu.options_home);
</code></pre>
<p>This results in something like </p>
<p><img src="https://i.stack.imgur.com/uvzvE.png" alt="enter image description here"></p>
<p>Is there a way to change this text color <em>without</em> using an image, changing the rest of the Toolbar text color, or by adding a custom view to the toolbar? Looking for an answer for minSdk 15 (appcompat).</p>
<p><strong>Update:</strong></p>
<p>My relevant style:</p>
<pre><code><style name="AppTheme" parent="AppTheme.Base">
<item name="actionMenuTextColor">@color/ww_red</item>
</style>
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/red</item>
<item name="colorAccent">@color/theme_accent</item>
<item name="android:textColor">@color/text_dark</item>
<item name="android:colorEdgeEffect">@color/gray</item>
</style>
</code></pre> | 28,579,867 | 6 | 9 | null | 2015-02-05 20:00:32.583 UTC | 12 | 2018-08-03 07:19:14.003 UTC | 2015-02-18 17:03:40.653 UTC | null | 413,254 | null | 413,254 | null | 1 | 49 | android|android-toolbar | 58,316 | <p>In your theme file you have to put this :</p>
<pre><code><style name="AppTheme.ActionBar" parent="Theme.AppCompat.Light.DarkActionBar">
...
<item name="actionMenuTextColor">@color/text_color</item>
...
</style>
</code></pre>
<p>and apply this theme to your Toolbar view like this :</p>
<pre><code><android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:layout_gravity="top"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:theme="@style/AppTheme.ActionBar"/>
</code></pre>
<p><strong>android:theme="@style/AppTheme.ActionBar"</strong> don't forget this line in your toolbar</p> |
10,157,122 | Object creation on the stack/heap? | <p>The following code creates an object on the stack:</p>
<pre><code>Object o;
</code></pre>
<p>When creating an object on the heap we can use:</p>
<pre><code>Object* o;
o = new Object();
</code></pre>
<p>rather than:</p>
<pre><code>Object* o = new Object();
</code></pre>
<p>When we split the heap object-creation over two lines and call the constructor on the second line (<code>o = new object()</code>), does this mean in the first line (<code>Object* o</code>) the pointer was created on the stack? So <code>Object o</code> puts the object on the stack, whereas <code>Object* o</code> puts the pointer to a future object on the stack?</p>
<p>My second question involves if the two lines of code were called outside of a class. I recently read (<a href="https://stackoverflow.com/questions/1169858/global-memory-management-in-c-in-stack-or-heap">Global memory management in C in stack or heap?</a>) that global variables are not contained on the stack/heap but actually another part of memory? If this is the case, would <code>Object* o</code> create a pointer which would sit in this other part of the memory and it points to the heap object?</p> | 10,157,210 | 7 | 3 | null | 2012-04-14 20:31:47.263 UTC | 61 | 2021-07-02 21:33:18.397 UTC | 2021-07-02 21:33:18.397 UTC | null | 5,459,839 | null | 997,112 | null | 1 | 68 | c++|initialization|heap-memory|stack-memory | 133,742 | <p>Actually, neither statement says anything about heap or stack. The code</p>
<pre><code>Object o;
</code></pre>
<p>creates one of the following, depending on its context:</p>
<ul>
<li>a local variable with automatic storage,</li>
<li>a static variable at namespace or file scope,</li>
<li>a member variable that designates the subobject of another object.</li>
</ul>
<p>This means that the storage location is determined by the context in which the object is defined. In addition, the C++ standard does not talk about stack <em>vs</em> heap storage. Instead, it talks about <a href="https://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration" rel="noreferrer">storage duration</a>, which can be either <em>automatic</em>, <em>dynamic</em>, <em>static</em> or <em>thread-local</em>. However, most implementations implement automatic storage via the call stack, and dynamic storage via the heap.</p>
<p>Local variables, which have automatic storage, are thus created on the stack. Static (and thread-local) objects are generally allocated in their own memory regions, neither on the stack nor on the heap. And member variables are allocated wherever the object they belong to is allocated. They have their containing object’s storage duration.</p>
<p>To illustrate this with an example:</p>
<pre><code>struct Foo {
Object o;
};
Foo foo;
int main() {
Foo f;
Foo* p = new Foo;
Foo* pf = &f;
}
</code></pre>
<p>Now where is the object <code>Foo::o</code> (that is, the subobject <code>o</code> of an object of class <code>Foo</code>) created? It depends:</p>
<ul>
<li><code>foo.o</code> has static storage because <code>foo</code> has static storage, and therefore lives neither on the stack nor on the heap.</li>
<li><code>f.o</code> has automatic storage since <code>f</code> has automatic storage (= it lives on the stack).</li>
<li><code>p->o</code> has dynamic storage since <code>*p</code> has dynamic storage (= it lives on the heap).</li>
<li><code>pf->o</code> is the same object as <code>f.o</code> because <code>pf</code> points to <code>f</code>.</li>
</ul>
<p>In fact, both <code>p</code> and <code>pf</code> in the above have automatic storage. A pointer’s storage is indistinguishable from any other object’s, it is determined by context. Furthermore, the initialising expression has no effect on the pointer storage.</p>
<p>The <em>pointee</em> (= what the pointer points to) is a completely different matter, and could refer to any kind of storage: <code>*p</code> is dynamic, whereas <code>*pf</code> is automatic.</p> |
63,087,217 | Changes using mutable reference of a field are not reflected after move of the original instance | <p>I was trying to manipulate the field <code>x</code> of the struct <code>Foo</code> by borrowing a mutable reference from its instance <code>foo</code>.</p>
<p>If I try to print the field <code>x</code> using the moved binding <code>y</code> of the instance <code>foo</code> <strong>after</strong> the move of the original instance, it keeps printing the value that haven't changed.</p>
<p>Simplified example below:</p>
<pre class="lang-rust prettyprint-override"><code>struct Foo {
x: i32,
}
fn main() {
let mut foo = Foo { x: 42 };
let x = &mut foo.x;
*x = 13;
let y = foo;
println!("{}", y.x); // -> 42; expected result: 13
}
</code></pre>
<p>Instead, if I print the moved binding <code>y</code> itself, it prints the changed value.</p>
<pre class="lang-rust prettyprint-override"><code>println!("{:?}", y); // -> Foo { x: 13 }
</code></pre>
<p>Or, if I print something else like <code>x</code> or <code>foo.x</code> <strong>before</strong> the move, it prints the thing as expected.</p>
<pre class="lang-rust prettyprint-override"><code>println!("{}", x); // -> 13
let y = foo;
println!("{}", y.x); // -> 13
</code></pre>
<p>Is this an intended behavior?</p> | 63,088,374 | 1 | 8 | null | 2020-07-25 10:27:06.4 UTC | 4 | 2020-08-15 10:19:06.363 UTC | 2020-07-25 18:59:00.807 UTC | null | 2,470,818 | null | 13,992,031 | null | 1 | 61 | rust|reference|move | 5,790 | <p>This is a known bug in the compiler which only affects rustc 1.45. rustc 1.44 is not affected and the issue has already been fixed on Beta which means it will be fixed on rustc 1.46.</p>
<p>An issue <a href="https://github.com/rust-lang/rust/issues/74739" rel="nofollow noreferrer">has been opened</a> to track it.</p>
<p>While this issue seem critical, it is very unlikely to be found in real code according to <a href="https://github.com/oli-obk" rel="nofollow noreferrer">oli-obk</a>, one of the main contributor to rustc, and in particular on <code>const</code> expressions:</p>
<blockquote>
<p>The bug is almost impossible to trigger on real world code. You need all values that are going into the bug to be constant values and there can't be any control flow or function calls in between.</p>
</blockquote>
<p>Version 1.45.1 <a href="https://blog.rust-lang.org/2020/07/30/Rust-1.45.1.html" rel="nofollow noreferrer">has been released</a> and contains a <a href="https://github.com/rust-lang/rust/pull/74746" rel="nofollow noreferrer">backport of the fix from beta</a>, among other things. Later version <a href="https://blog.rust-lang.org/2020/08/03/Rust-1.45.2.html" rel="nofollow noreferrer">1.45.2</a> was released with more (unrelated) fixes.</p> |
7,846,268 | Javascript click event handler - how do I get the reference to the clicked item? | <p>My HTML:</p>
<pre><code><div id="x" onclick="clickHandler(event)">
<div id="button1">This turns green</div>
<div id="button2">This turns blue</div>
</div>
</code></pre>
<p>So first of all, why am I supposed to be passing "event" into the click handler and is event some kind of system keyword?
Also, since the click handler is identified on the container div, how do I know which button has been clicked?</p> | 7,846,290 | 3 | 0 | null | 2011-10-21 07:27:27.547 UTC | 12 | 2019-05-30 20:31:32.45 UTC | 2016-01-20 14:50:28.727 UTC | null | 3,853,934 | null | 1,004,278 | null | 1 | 31 | javascript|html|event-handling|click | 65,044 | <p><code>event</code> is an Event object which is created automatically when an event is fired. Note that you don't have to call it <code>event</code> (I tend to call it simply <code>e</code>). That Event object has a number of properties which describe the event it represents. In this case, the one you're interested in would be <code>target</code>, which shows the element that was the source of the event:</p>
<pre><code>function clickHandler(e) {
var target = e.target;
}
</code></pre>
<p>Here's a <a href="http://jsfiddle.net/LGmEp/6/" rel="noreferrer">working example</a>.</p>
<p>Unfortunately, it's never quite that simple. While the specification says it should be <code>event.target</code>, Internet Explorer likes to be different, and chooses to use <code>event.srcElement</code>, so you probably want to put in a check to make sure <code>event.target</code> exists! For example:</p>
<pre><code>function clickHandler(e) {
var target = (e.target) ? e.target : e.srcElement;
}
</code></pre> |
11,792,812 | calling a class in another project Eclipse | <p>I have a project "A" and I need to call a class "c" from another project "B".</p>
<p>I have done the following. Click in "A" -->Properties -->Build Path --> and in one tab of Java Source I selected the project B. --> Accept</p>
<p>Now I can create objets of Class "c" but when I run the project I get "ClassNotFoundException"</p>
<p><strong>Update,</strong></p>
<p>I keep getting java.lang.ClassNotFoundException.</p>
<p>In "JSF" -->Properties -->Build Path --> Projects ---> I Added the Project:</p>
<p><img src="https://i.stack.imgur.com/uXiNi.jpg" alt="enter image description here"></p>
<p>In Run --> Run Configurations --> ClassPath I had:</p>
<p><img src="https://i.stack.imgur.com/ENMlX.jpg" alt="enter image description here"></p>
<p>and now I have added the project "JIRA" and "JIRA dependencies"
<img src="https://i.stack.imgur.com/OnJiG.png" alt="enter image description here"></p>
<p>JIRA project has this dependencies:</p>
<p><img src="https://i.stack.imgur.com/vnB1y.jpg" alt="enter image description here"></p>
<p>And I get the following error:</p>
<p><img src="https://i.stack.imgur.com/JxrQo.jpg" alt="enter image description here"></p>
<p>but this class is in M2_REPO:</p>
<p><img src="https://i.stack.imgur.com/ivTtK.jpg" alt="enter image description here"></p>
<p><strong>SOLUTION</strong></p>
<p>I add "JIRA dependencies" only in JARs without Maven:
<img src="https://i.stack.imgur.com/txbKW.jpg" alt="enter image description here">
and now it´s run.</p> | 11,792,884 | 7 | 2 | null | 2012-08-03 09:17:16.12 UTC | 3 | 2016-02-22 14:11:44.9 UTC | 2012-08-04 12:57:19.503 UTC | null | 1,504,721 | null | 1,504,721 | null | 1 | 14 | java|eclipse | 47,425 | <p>You need to add project B to the Run configuration used by project A. In the menu Run -> Run configurations... , add the project B in the tab 'classpath' of your run configuration. </p> |
11,464,578 | R: Subsetting a data frame using a list of dates as the filter | <p>I have a data frame with a date column and some other value columns. I would like to extract from the data frame those rows in which the date column matches any of the elements in a pre-existing list of dates. For example, using a list of one element, the date '2012-01-01' would pull the row with a date of '2012-01-01' from the data frame.</p>
<p>For numbers I think I know how to match the values. This code:</p>
<pre><code>testdf <- data.frame(mydate = seq(as.Date('2012-01-01'),
as.Date('2012-01-10'), by = 'day'),
col1 = 1:10,
col2 = 11:20,
col3 = 21:30)
</code></pre>
<p>...produces this data frame:</p>
<pre><code> mydate col1 col2 col3
1 2012-01-01 1 11 21
2 2012-01-02 2 12 22
3 2012-01-03 3 13 23
4 2012-01-04 4 14 24
5 2012-01-05 5 15 25
6 2012-01-06 6 16 26
7 2012-01-07 7 17 27
8 2012-01-08 8 18 28
9 2012-01-09 9 19 29
10 2012-01-10 10 20 30
</code></pre>
<p>I can do this:</p>
<pre><code>testdf[which(testdf$col3 %in% c('25','29')),]
</code></pre>
<p>which produces this:</p>
<pre><code> mydate col1 col2 col3
5 2012-01-05 5 15 25
9 2012-01-09 9 19 29
</code></pre>
<p>I can generalise this to a list like this:</p>
<pre><code>myvalues <- c('25','29')
testdf[which(testdf$col3 %in% myvalues),]
</code></pre>
<p>And I get the same output. So I had thought I would be able to use the same approach for dates, but it appears that I was wrong. Doing this:</p>
<pre><code>testdf[which(testdf$mydate %in% c('2012-01-05','2012-01-09')),]
</code></pre>
<p>Gets me this:</p>
<pre><code>[1] mydate col1 col2 col3
<0 rows> (or 0-length row.names)
</code></pre>
<p>And popping the dates in their own list - which is the ultimate aim - doesn't help either. I can think of ways round this with loops or an apply function, but it seems to me that there must be a simpler way for what is probably a fairly common requirement. Is it that I have again overlooked something simple?</p>
<p><strong>Q: How can I subset those rows of a data frame that have a date column the values of which match one of a list of dates?</strong></p> | 11,464,622 | 3 | 2 | null | 2012-07-13 05:22:59.447 UTC | 10 | 2013-07-27 08:38:05.817 UTC | 2013-07-27 08:38:05.817 UTC | null | 952,708 | null | 952,708 | null | 1 | 25 | r | 48,054 | <p>You have to convert the date <code>string</code> into a <code>Date</code> variable using <code>as.Date</code> (try <code>?as.Date</code> at the console). Bonus: you can drop which:</p>
<pre><code>> testdf[testdf$mydate %in% as.Date(c('2012-01-05', '2012-01-09')),]
mydate col1 col2 col3
5 2012-01-05 5 15 25
9 2012-01-09 9 19 29
</code></pre> |
11,617,209 | How to execute multiple SQL queries in MySQL Workbench? | <p>I am using MySQL Workbench CE for Windows version 5.2.40.</p>
<p>I want to execute the following SQL queries together. However I can only execute the SQL queries by first executing the <code>CREATE TABLE</code> query, and then executing the <code>INSERT INTO</code> query and after that executing the <code>SELECT</code> query. </p>
<pre><code>CREATE TABLE testTable(
Name VARCHAR(20),
Address VARCHAR(50),
Gender VARCHAR(10)
)
INSERT INTO testTable
VALUES
('Derp', 'ForeverAlone Street', 'Male'),
('Derpina', 'Whiterun Breezehome', 'Female')
Select * FROM testTable
</code></pre>
<p>So how do I execute the <code>CREATE TABLE</code>, <code>INSERT INTO</code> and the <code>SELECT</code> queries by one click?</p> | 11,617,240 | 2 | 1 | null | 2012-07-23 17:10:55.94 UTC | 1 | 2018-04-20 18:55:59.153 UTC | 2012-07-23 17:28:02.76 UTC | null | 168,493 | null | 1,546,445 | null | 1 | 28 | mysql|sql|mysql-workbench | 65,424 | <p>Add a semicolon after each statement:</p>
<pre><code>CREATE TABLE testTable(
Name VARCHAR(20),
Address VARCHAR(50),
Gender VARCHAR(10)
);
INSERT INTO testTable
VALUES
('Derp', 'ForeverAlone Street', 'Male'),
('Derpina', 'Whiterun Breezehome', 'Female');
SELECT * FROM testTable;
</code></pre> |
19,971,221 | Keyboard shortcut to switch between python console and the editor in pycharm | <p>In general, I'd like to know the keyboard shortcut for navigating to multiple sections like the project structure, editor, console. I'm using eclipse keymap configuration in pycharm. I used to switch between different views in eclipse using [<kbd>Ctrl</kbd> + <kbd>F7</kbd>]. But that is not working in pycharm.</p>
<p>I also used to use <kbd>F12</kbd> to bring the focus back to the editor when the focus is on any other view. That is also not working in pycharm.</p>
<p>Environment: Ubuntu 12.04 64bit.</p> | 27,404,192 | 15 | 4 | null | 2013-11-14 06:39:29.673 UTC | 14 | 2020-04-18 07:12:15.04 UTC | 2020-03-13 14:37:26.17 UTC | null | 9,403,827 | null | 434,678 | null | 1 | 58 | pycharm | 32,618 | <p>In Pycharm 4, you can specify shortcuts with</p>
<p><strong>File / Settings / Appearance and Behaviour / Keymap</strong></p>
<p>You can create any shortcut you like, and bind it to the command "Python Console" (search for Console), which has no default keymapping. Be aware that it is possible to have multiple consoles open at the same time (for example if you open one in the debugging window) so this may not always behave as you expect it to.</p>
<p>You can toggle back to the last editor window by hitting escape.</p> |
61,385,454 | How to post multiple Axios requests at the same time? | <p>At this moment I have a webpage in which a long list of Axios POST calls are being made. Now, the requests seem to be sent in parallel (JavaScript continues sending the next request before the result is received). </p>
<p>However, the results seem to be returned one by one, not simultaneously. Let's say one POST call to the PHP script takes 4 seconds and I need to make 10 calls. It would currently take 4 seconds per call, which would be 40 seconds in total. I hope to find a solution to both and receive all results at approximately the same time (~4 seconds) instead of ~40 seconds.</p>
<p>Now I've read about threads, multithreading in NodeJS using Workers. I've read that JavaScript itself is only single-threaded, so it may not allow this by itself.</p>
<p>But I'm not sure where to go from here. All I have are some ideas. I'm not sure whether or not I'm heading into the right direction and if I am, I am not sure how to use Workers in NodeJS and apply it in my code. Which road should I take? Any guidance would be highly appreciated!</p>
<p>Here is a small piece of example code:</p>
<pre><code>for( var i = 0; i < 10; i++ )
{
window.axios.post(`/my-url`, {
myVar: 'myValue'
})
.then((response) => {
// Takes 4 seconds, 4 more seconds, 4 more seconds, etc
// Ideally: Takes 4 seconds, returns in the same ~4 seconds, returns in the same ~4 seconds, etc
console.log( 'Succeeded!' );
})
.catch((error) => {
console.log( 'Error' );
});
// Takes < 1 second, < 1 more second, < 1 more second, etc
console.log( 'Request sent!' );
}
</code></pre> | 61,588,558 | 7 | 3 | null | 2020-04-23 10:52:56.887 UTC | 20 | 2022-02-03 07:56:48.343 UTC | null | null | null | null | 5,437,864 | null | 1 | 37 | javascript|node.js|multithreading|axios | 71,895 | <p>There are three cases via you can achieve your goal.</p>
<ol>
<li><p>For simultaneous requests with Axios, you can use <code>Axios.all()</code></p>
<pre><code> axios.all([
axios.post(`/my-url`, {
myVar: 'myValue'
}),
axios.post(`/my-url2`, {
myVar: 'myValue'
})
])
.then(axios.spread((data1, data2) => {
// output of req.
console.log('data1', data1, 'data2', data2)
}));
</code></pre>
</li>
<li><p>you can use <code>Promise.allSettled()</code>. The Promise.allSettled() method returns a promise that resolves after all of the given promises have either resolved or rejected,</p>
</li>
<li><p>You can try to use <code>Promise.all()</code> but it has the drawback that if any <strong>1</strong> req failed then it will fail for all and give o/p as an error(or in catch block)</p>
</li>
</ol>
<p>but the best case is the first one.</p> |
3,741,863 | EditText Label? | <p>I want to have some layout a bit like this</p>
<pre><code>[text tabel][edittext]
</code></pre>
<p>i cant find an attribute like html esque label. It seems to be the case that i need to use </p>
<pre><code>[TextView][EditText]
</code></pre>
<p>but i cant get them to go on the same line this is my xml file.</p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">"
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/boat_1"/>
<EditText
android:id="@+id/entry"
android:hint="@string/IRC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/boat_2"/>
<EditText
android:id="@+id/entry"
android:hint="@string/IRC"
android:minWidth="100dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background"/>
<Button android:id="@+id/close"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="@string/title_close" />
</code></pre>
<p></p> | 3,741,872 | 4 | 1 | null | 2010-09-18 13:28:43.483 UTC | 10 | 2020-09-27 11:07:27.52 UTC | 2012-06-26 05:17:34.4 UTC | null | 750,613 | null | 296,051 | null | 1 | 27 | android|android-edittext | 82,066 | <p>You have basically two options:</p>
<h2>Option 1: Use nested LinearLayouts:</h2>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/boat_1"/>
<EditText
android:id="@+id/entry"
android:hint="@string/IRC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/boat_2"/>
<EditText
android:id="@+id/entry"
android:hint="@string/IRC"
android:minWidth="100dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background"/>
</LinearLayout>
<Button android:id="@+id/close"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="@string/title_close" />
</code></pre>
<p>Notice that I'm using <code>android:orientation="horizontal"</code> for those nested layouts.</p>
<h2>Option 2: you can use another content manager, like <code>RelativeLayout</code>.</h2>
<p>The advantage of this, is that you can avoid nesting, thus your layout will be easier to read/maintain/inflate. This is a brief example:</p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/text_view_boat1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/boat_1"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"/>
<EditText
android:id="@+id/entry"
android:hint="@string/IRC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background"
android:layout_toRightOf="@+id/text_view_boat1"
android:layout_alignParentTop="true"/>
<TextView
android:id="@+id/text_view_boat2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/boat_2"
android:layout_alignParentLeft="true"
android:layout_below="@id/text_view_boat1"/>
<EditText
android:id="@+id/entry2"
android:hint="@string/IRC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background"
android:layout_toRightOf="@+id/text_view_boat2"
android:layout_below="@id/entry"/>
</RelativeLayout>
</code></pre> |
3,913,638 | How can I get a list of build targets in Ant? | <p>My codebase has a long <code>build.properties</code> file written by someone else. I want to see the available built targets without having to search through the file manually. Does ant have a command for this - something like <code>ant show-targets</code> - that will make it list all the targets in the build file?</p> | 3,913,671 | 4 | 0 | null | 2010-10-12 10:26:01.803 UTC | 32 | 2019-05-15 07:52:03.497 UTC | 2013-08-24 01:01:21.903 UTC | null | 244,494 | null | 390,230 | null | 1 | 203 | ant | 71,047 | <p>The <code>-p</code> or <code>-projecthelp</code> option does exactly this, so you can just try:</p>
<pre><code>ant -p build.xml
</code></pre>
<p>From ant's command line <a href="http://ant.apache.org/manual/running.html" rel="noreferrer">documentation</a>:</p>
<blockquote>
<p>The <code>-projecthelp</code> option prints out a list of the build file's targets. Targets that include a <code>description</code> attribute are listed as "Main targets", those without a <code>description</code> are listed as "Other targets", then the "Default" target is listed ("Other targets" are only displayed if there are no main targets, or if Ant is invoked in <code>-verbose</code> or <code>-debug</code> mode). </p>
</blockquote> |
3,340,192 | DataGridView bound to BindingList does not refresh when value changed | <p>I have a DataGridView bound to a BindingList (C# Windows Forms). If I change one of the values in an item in the list it does not immediately show up in the grid. If I click on the changed cell, or minimize then maximize the window it updates properly, but I need it to happen automatically.</p>
<p>I had the same problem earlier, but in that situation I had to change the cell's background colour at the same time that the value changed. This caused the cell to refresh correctly.</p>
<p>The only way I can get it to work is...</p>
<pre><code>dataGridView.DataSource = null;
dataGridView.DataSource = myBindingList
</code></pre>
<p>...but I'd really like to avoid this as it makes the scrollbar pop back to the top, and means that I'd have to set my cell background colours again. Surely there's a better way. I've tried Refresh (as well as refreshing the parent), Update, and Invalidate, but they're not doing what I need.</p>
<p>I've seen this problem mentioned on a few message boards, but haven't seen a working answer to it yet.</p> | 3,439,634 | 5 | 0 | null | 2010-07-27 01:36:55.207 UTC | 8 | 2015-03-25 21:18:08.977 UTC | 2010-07-27 01:45:10.48 UTC | null | 399,388 | null | 399,388 | null | 1 | 21 | c#|winforms|data-binding|datagridview | 52,193 | <blockquote>
<p><code>ListChanged</code> notifications for item value changes are only raised if the list item type implements the <code>INotifyPropertyChanged</code> interface.</p>
</blockquote>
<p>Taken from: <a href="http://msdn.microsoft.com/en-us/library/ms132742.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms132742.aspx</a></p>
<p>So my first question would be: Implements your item the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx" rel="noreferrer"><code>INotifyPropertyChanged</code></a> properly?</p> |
3,236,213 | Is there a direct equivalent in Java for Python's str.join? | <blockquote>
<p><strong>Possible Duplicates:</strong><br>
<a href="https://stackoverflow.com/questions/63150/whats-the-best-way-to-build-a-string-of-delimited-items-in-java">What’s the best way to build a string of delimited items in Java?</a><br>
<a href="https://stackoverflow.com/questions/1751844/java-convert-liststring-to-a-joind-string">Java: convert List<String> to a join()d string</a> </p>
</blockquote>
<p>In Java, given a collection, getting the iterator and doing a separate case for the first (or last) element and the rest to get a comma separated string seems quite dull, is there something like <code>str.join</code> in Python?</p>
<p>Extra clarification for avoiding it being closed as duplicate: I'd rather not use external libraries like Apache Commons.</p>
<p>Thanks!</p>
<h2>update a few years after...</h2>
<p><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.CharSequence...-" rel="noreferrer">Java 8 came to the rescue</a></p> | 3,236,306 | 5 | 6 | null | 2010-07-13 10:29:53.837 UTC | 2 | 2020-06-22 05:35:11.76 UTC | 2017-05-23 12:32:06.76 UTC | null | -1 | null | 106,979 | null | 1 | 30 | java|python|string | 13,636 | <p>For a long time Java offered no such method. Like many others I did my versions of such join for array of strings and collections (iterators).</p>
<p>But Java 8 added <code>String.join()</code>:</p>
<pre><code>String[] arr = { "ala", "ma", "kota" };
String joined = String.join(" ", arr);
System.out.println(joined);
</code></pre> |
3,282,103 | Understanding Lambda expressions and delegates | <p>I have been trying to figure this out for quite sometime (reading online blogs and articlaes), but so far unsuccessful. </p>
<p>What are delegates? What are Lambda Expressions? Advantages and disadvantages of both? Possible best practice of when to use one or the other?</p>
<p>Thanks in advance.</p> | 3,282,205 | 6 | 5 | null | 2010-07-19 14:43:19.147 UTC | 12 | 2012-04-03 19:03:43.427 UTC | 2010-07-19 14:59:42.413 UTC | null | 279,521 | null | 279,521 | null | 1 | 15 | c#|.net-3.5|delegates|lambda | 28,386 | <p>Delegates are methods that you can use as variables, like strings etc. For example you can declare a delegate method with one argument:</p>
<pre>delegate void OneArgumentDelegate(string argument);</pre>
<p>It doesn't do anything, much like an interface. If you have a method in any class with one argument like this:</p>
<pre>void SomeMethod(string someArgument) {}</pre>
<p>It <i>matches</i> the signature of the delegate, and thus can be assigned to a variable of its type:</p>
<pre>OneArgumentDelegate ThisIsAVariable = new OneArgumentDelegate(SomeMethod);
OneArgumentDelegate ThisIsAlsoAVariable = SomeMethod; // Shorthand works too</pre>
<p>These can then be passed as arguments to methods and invoked, like so:</p>
<pre>void Main()
{
DoStuff(PrintString);
}
void PrintString(string text)
{
Console.WriteLine(text);
}
void DoStuff(OneArgumentDelegate action)
{
action("Hello!");
}</pre>
<p>This will output <code>Hello!</code>.</p>
<p>Lambda expressions are a shorthand for the <code>DoStuff(PrintString)</code> so you don't have to create a method for every delegate variable you're going to use. You 'create' a temporary method that's passed on to the method. It works like this:</p>
<pre>DoStuff(string text => Console.WriteLine(text)); // single line
DoStuff(string text => // multi line
{
Console.WriteLine(text);
Console.WriteLine(text);
});</pre>
<p>Lambda expressions are just a shorthand, you might as well create a seperate method and pass it on. I hope you understand it better now ;-)</p> |
3,841,323 | rails page titles | <p>I don't like the way rails does page titles by default (just uses the controller name), so I'm working on a new way of doing it like so:</p>
<p>application controller:</p>
<pre><code>def page_title
"Default Title Here"
end
</code></pre>
<p>posts controller:</p>
<pre><code>def page_title
"Awesome Posts"
end
</code></pre>
<p>application layout:</p>
<pre><code><title><%=controller.page_title%></title>
</code></pre>
<p>It works well because if I don't have a page_title method in whatever controller I'm currently using it falls back to the default in the application controller. But what if in my users controller I want it to return "Signup" for the "new" action, but fall back for any other action? Is there a way to do that?</p>
<p>Secondly, does anyone else have any other ways of doing page titles in rails?</p> | 3,841,549 | 6 | 0 | null | 2010-10-01 16:51:47.41 UTC | 16 | 2021-07-15 20:26:41.097 UTC | 2014-02-08 10:25:42.537 UTC | null | 727,208 | null | 202,875 | null | 1 | 26 | html|ruby-on-rails|title|erb | 15,864 | <p>I disagree with the other answers, I believe the title shouldn't be set per action, but rather within the view itself. Keep the view logic within the view and the controller logic within the controller.</p>
<p>Inside your <code>application_helper.rb</code> add:</p>
<pre><code>def title(page_title)
content_for(:title) { page_title }
end
</code></pre>
<p>Then to insert it into your <code><title></code>:</p>
<pre><code><title><%= content_for?(:title) ? content_for(:title) : "Default Title" %></title>
</code></pre>
<p>So when you are in your views, you have access to all instance variables set from the controller and you can set it there. It keeps the clutter out of the controller as well.</p>
<pre><code><%- title "Reading #{@post.name}" %>
</code></pre> |
3,596,622 | Negative NaN is not a NaN? | <p>While writing some test cases, and some of the tests check for the result of a NaN.</p>
<p>I tried using <code>std::isnan</code> but the assert failes:</p>
<pre><code>Assertion `std::isnan(x)' failed.
</code></pre>
<p>After printing the value of <code>x</code>, it turned out it's negative NaN (<code>-nan</code>) which is totally acceptable in my case.</p>
<p>After trying to use the fact that <code>NaN != NaN</code> and using <code>assert(x == x)</code>, the compiler does me a 'favor' and optimises the assert away.</p>
<p>Making my own <code>isNaN</code> function is being optimised away as well.</p>
<p>How can I check for both equality of NaN <em>and</em> -NaN?</p> | 3,596,747 | 6 | 13 | null | 2010-08-29 21:13:31.037 UTC | 6 | 2022-07-04 23:05:36.07 UTC | 2016-11-20 00:09:48.567 UTC | null | 1,593,077 | null | 41,983 | null | 1 | 34 | c++|nan|fast-math | 14,344 | <p>This is embarrassing.</p>
<p>The reason the compiler (GCC in this case) was optimising away the comparison and <code>isnan</code> returned <code>false</code> was because someone in my team had turned on <code>-ffast-math</code>.</p>
<p>From the docs:</p>
<pre>
-ffast-math
Sets -fno-math-errno, -funsafe-math-optimizations, -fno-trapping-math,
-ffinite-math-only, -fno-rounding-math, -fno-signaling-nans and
fcx-limited-range.
This option causes the preprocessor macro __FAST_MATH__ to be defined.
This option should never be turned on by any -O option since it can result in
incorrect output for programs which depend on an exact implementation of IEEE
or ISO rules/specifications for math functions.
</pre>
<p>Notice the ending sentence - <code>-ffast-math</code> is unsafe.</p> |
3,950,839 | tar: Error is not recoverable: exiting now | <p>when I untar doctrine</p>
<pre><code>-rw-r--r-- 1 root root 660252 2010-10-16 23:06 Doctrine-1.2.0.tgz
</code></pre>
<p>I always get this error messages</p>
<pre><code>root@X100e:/usr/local/lib/Doctrine/stable# tar -xvzf Doctrine-1.2.0.tgz
.
.
.
Doctrine-1.2.0/tests/ViewTestCase.php
Doctrine-1.2.0/CHANGELOG
gzip: stdin: decompression OK, trailing garbage ignored
Doctrine-1.2.0/COPYRIGHT
Doctrine-1.2.0/LICENSE
tar: Child returned status 2
tar: Error is not recoverable: exiting now
</code></pre>
<p>The untar operation works, but I always get this error messages.</p>
<p>Any clues what I do wrong?</p> | 3,950,958 | 7 | 0 | null | 2010-10-16 21:18:41.153 UTC | 5 | 2022-06-24 01:39:04.177 UTC | 2021-01-12 07:22:35.16 UTC | null | 9,431,571 | null | 420,953 | null | 1 | 38 | linux|doctrine|compression|gzip|tar | 222,069 | <p>I would try to unzip and untar separately and see what happens:</p>
<pre><code>mv Doctrine-1.2.0.tgz Doctrine-1.2.0.tar.gz
gunzip Doctrine-1.2.0.tar.gz
tar xf Doctrine-1.2.0.tar
</code></pre> |
4,032,104 | HTTP Ajax Request via HTTPS Page | <p>I am having a site with some pages on HTTPS connection. From these HTTPS pages, I have to use a HTTP Ajax request for some errors retrieval like blank fields. But this error messages are not coming. Is there any solution to it or I have to make that AJAX request to file on HTTPS connection?</p> | 4,032,123 | 7 | 3 | null | 2010-10-27 10:16:10.383 UTC | 14 | 2021-03-14 22:21:33.303 UTC | 2016-08-31 09:06:34.53 UTC | null | 95,353 | null | 344,054 | null | 1 | 47 | javascript|ajax | 146,463 | <p>This is not possible due to the <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy" rel="noreferrer">Same Origin Policy</a>. </p>
<p>You will need to switch the Ajax requests to https, too.</p> |
3,525,581 | How to align footer (div) to the bottom of the page? | <p>Can anyone explain how to align a footer div to the bottom of the page. From the examples I've seen, they all show how to make the div stay visible at the bottom, no matter where you've scrolled the page. Although I don't want it like that. I want it fixed at the bottom of the page, so it doesn't move. Appreciate the help!</p> | 3,525,675 | 7 | 2 | null | 2010-08-19 19:39:14.223 UTC | 19 | 2021-05-15 21:24:13.1 UTC | null | null | null | null | 303,221 | null | 1 | 88 | html|css|footer|alignment | 365,257 | <p><strong>UPDATE</strong></p>
<p>My original answer is from a long time ago, and the links are broken; updating it so that it continues to be useful.</p>
<p>I'm including updated solutions inline, as well as a working examples on JSFiddle. Note: I'm relying on a CSS reset, though I'm not including those styles inline. Refer to <a href="https://necolas.github.io/normalize.css/" rel="noreferrer">normalize.css</a></p>
<p><strong>Solution 1 - margin offset</strong></p>
<p><a href="https://jsfiddle.net/UnsungHero97/ur20fndv/2/" rel="noreferrer">https://jsfiddle.net/UnsungHero97/ur20fndv/2/</a></p>
<p><strong>HTML</strong></p>
<pre><code><div id="wrapper">
<div id="content">
<h1>Hello, World!</h1>
</div>
</div>
<footer id="footer">
<div id="footer-content">Sticky Footer</div>
</footer>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>html, body {
margin: 0px;
padding: 0px;
min-height: 100%;
height: 100%;
}
#wrapper {
background-color: #e3f2fd;
min-height: 100%;
height: auto !important;
margin-bottom: -50px; /* the bottom margin is the negative value of the footer's total height */
}
#wrapper:after {
content: "";
display: block;
height: 50px; /* the footer's total height */
}
#content {
height: 100%;
}
#footer {
height: 50px; /* the footer's total height */
}
#footer-content {
background-color: #f3e5f5;
border: 1px solid #ab47bc;
height: 32px; /* height + top/bottom paddding + top/bottom border must add up to footer height */
padding: 8px;
}
</code></pre>
<p><strong>Solution 2 - flexbox</strong></p>
<p><a href="https://jsfiddle.net/UnsungHero97/oqom5e5m/3/" rel="noreferrer">https://jsfiddle.net/UnsungHero97/oqom5e5m/3/</a></p>
<p><strong>HTML</strong></p>
<pre><code><div id="content">
<h1>Hello, World!</h1>
</div>
<footer id="footer">Sticky Footer</footer>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>html {
height: 100%;
}
body {
display: flex;
flex-direction: column;
min-height: 100%;
}
#content {
background-color: #e3f2fd;
flex: 1;
padding: 20px;
}
#footer {
background-color: #f3e5f5;
padding: 20px;
}
</code></pre>
<p>Here's some links with more detailed explanations and different approaches:</p>
<ul>
<li><a href="https://css-tricks.com/couple-takes-sticky-footer/" rel="noreferrer">https://css-tricks.com/couple-takes-sticky-footer/</a></li>
<li><a href="https://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/" rel="noreferrer">https://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/</a></li>
<li><a href="http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page" rel="noreferrer">http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page</a></li>
</ul>
<hr>
<p><strong>ORIGINAL ANSWER</strong></p>
<p>Is this what you mean?</p>
<p><a href="http://ryanfait.com/sticky-footer/" rel="noreferrer">http://ryanfait.com/sticky-footer/</a></p>
<blockquote>
<p>This method uses only 15 lines of CSS and hardly any HTML markup. Even better, it's completely valid CSS, and it works in all major browsers. Internet Explorer 5 and up, Firefox, Safari, Opera and more.</p>
</blockquote>
<p>This footer will stay at the bottom of the page permanently. This means that if the content is more than the height of the browser window, you will need to scroll down to see the footer... but if the content is less than the height of the browser window, the footer will stick to the bottom of the browser window instead of floating up in the middle of the page.</p>
<p>Let me know if you need help with the implementation. I hope this helps.</p> |
3,789,442 | Mercurial - all files that changed in a changeset? | <p>How can you determine all the files that changed in a given changeset? </p>
<p>I'm not looking for a diff in this case, just a list of add/remove/modifications.</p>
<p><code>hg log -vprX</code> does a list of diffs but I just want the files.</p> | 3,789,516 | 7 | 1 | null | 2010-09-24 17:15:05.967 UTC | 19 | 2018-05-15 17:27:34.61 UTC | null | null | null | null | 47,281 | null | 1 | 102 | mercurial|diff|changeset | 61,307 | <p>If you want to list only files that have changed then you should be using "status command"
The following will list the changes to files in revision REV</p>
<pre><code>hg status --change REV
</code></pre> |
3,630,969 | Implement linked list in php | <p>How should I implement a linked list in PHP? Is there a implementation built in into PHP?</p>
<p>I need to do a lot of insert and delete operations, and at same time I need to preserve order. </p>
<p>I'd like to use only PHP without any special extensions.</p> | 3,631,057 | 8 | 1 | null | 2010-09-02 20:28:21.323 UTC | 10 | 2020-07-27 07:00:57.377 UTC | 2014-03-28 17:40:23.353 UTC | null | 445,131 | null | 196,561 | null | 1 | 22 | php|linked-list | 57,088 | <p>There is <a href="http://www.php.net/manual/en/class.spldoublylinkedlist.php" rel="noreferrer"><code>SplDoublyLinkedList</code></a>. Is this okay, too?</p> |
3,742,580 | Python, why elif keyword? | <p>I just started Python programming, and I'm wondering about the <code>elif</code> keyword.</p>
<p>Other programming languages I've used before use <code>else if</code>. Does anyone have an idea why the Python developers added the additional <code>elif</code> keyword?</p>
<p>Why not:</p>
<pre><code>if a:
print("a")
else if b:
print("b")
else:
print("c")
</code></pre> | 3,742,598 | 8 | 11 | null | 2010-09-18 16:54:56.71 UTC | 10 | 2019-01-28 08:32:36.59 UTC | 2015-09-21 23:12:31.78 UTC | null | 1,709,587 | null | 268,127 | null | 1 | 68 | python|keyword | 38,915 | <p>Most likely it's syntactic sugar. Like the <code>Wend</code> of Visual Basic.</p> |
4,006,588 | Is it possible to use jQuery to get the width of an element in percent or pixels, based on what the developer specified with CSS? | <p>I'm writing a jQuery plugin and something I need to be able to do is determine the width of an element that the user specifies. The problem is that .width() or .css('width') will always report exact pixels, even if the developer has assigned it e.g. width:90% with CSS. </p>
<p>Is there any way to have jQuery output the width of an element in px or % depending on what the developer has given it with CSS?</p> | 4,006,610 | 10 | 1 | null | 2010-10-23 23:37:55.193 UTC | 13 | 2022-03-04 19:11:42.727 UTC | 2010-10-25 13:52:29.273 UTC | null | 344,164 | null | 344,164 | null | 1 | 50 | jquery|css|width | 78,513 | <p>I'd say the best way is to compute it yourself:</p>
<pre><code>var width = $('#someElt').width();
var parentWidth = $('#someElt').offsetParent().width();
var percent = 100*width/parentWidth;
</code></pre> |
3,403,644 | What is the purpose of XSD files? | <p>Since we can query on the XML file from C# (.NET), why do we need an XSD file? I know it is metadata file of particular XML file. We can specify the relationships in XSD, but what is its functioning then? </p>
<h2>XML</h2>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<Root>
<Customers>
<Customer CustomerID="GREAL">
<CompanyName>Great Lakes Food Market</CompanyName>
<ContactName>Howard Snyder</ContactName>
<ContactTitle>Marketing Manager</ContactTitle>
<Phone>(503) 555-7555</Phone>
<FullAddress>
<Address>2732 Baker Blvd.</Address>
<City>Eugene</City>
<Region>OR</Region>
<PostalCode>97403</PostalCode>
<Country>USA</Country>
</FullAddress>
</Customer>
</Customers>
<Orders>
<Order>
<CustomerID>GREAL</CustomerID>
<EmployeeID>6</EmployeeID>
<OrderDate>1997-05-06T00:00:00</OrderDate>
<RequiredDate>1997-05-20T00:00:00</RequiredDate>
<ShipInfo ShippedDate="1997-05-09T00:00:00">
<ShipVia>2</ShipVia>
<Freight>3.35</Freight>
<ShipName>Great Lakes Food Market</ShipName>
<ShipAddress>2732 Baker Blvd.</ShipAddress>
<ShipCity>Eugene</ShipCity>
<ShipRegion>OR</ShipRegion>
<ShipPostalCode>97403</ShipPostalCode>
<ShipCountry>USA</ShipCountry>
</ShipInfo>
</Order>
<Order>
<CustomerID>GREAL</CustomerID>
<EmployeeID>8</EmployeeID>
<OrderDate>1997-07-04T00:00:00</OrderDate>
<RequiredDate>1997-08-01T00:00:00</RequiredDate>
<ShipInfo ShippedDate="1997-07-14T00:00:00">
<ShipVia>2</ShipVia>
<Freight>4.42</Freight>
<ShipName>Great Lakes Food Market</ShipName>
<ShipAddress>2732 Baker Blvd.</ShipAddress>
<ShipCity>Eugene</ShipCity>
<ShipRegion>OR</ShipRegion>
<ShipPostalCode>97403</ShipPostalCode>
<ShipCountry>USA</ShipCountry>
</ShipInfo>
</Order>
</Orders>
</Root>
</code></pre>
<p>I want to get data from the <code>Order</code> elements according to a provided <code>CustomerID</code>.</p>
<p><strong>Also</strong>: What is the purpose of giving the relationships in XSD?</p> | 3,403,659 | 10 | 1 | null | 2010-08-04 08:00:24.97 UTC | 26 | 2019-06-26 12:49:10.307 UTC | 2018-09-29 18:14:21.62 UTC | null | 290,085 | null | 165,309 | null | 1 | 92 | xml|xsd | 192,859 | <p><a href="http://en.wikipedia.org/wiki/XML_Schema_%28W3C%29" rel="noreferrer">XSD</a> files are used to validate that XML files conform to a certain format.</p>
<p>In that respect they are similar to <a href="http://en.wikipedia.org/wiki/Document_Type_Definition" rel="noreferrer">DTD</a>s that existed before them.</p>
<p>The main difference between XSD and DTD is that XSD is written in XML and is considered easier to read and understand.</p> |
3,919,755 | How to parse $QUERY_STRING from a bash CGI script? | <p>I have a bash script that is being used in a CGI. The CGI sets the <code>$QUERY_STRING</code> environment variable by reading everything after the <code>?</code> in the URL. For example, <a href="http://example.com?a=123&b=456&c=ok" rel="noreferrer">http://example.com?a=123&b=456&c=ok</a> sets <code>QUERY_STRING=a=123&b=456&c=ok</code>.</p>
<p>Somewhere I found the following ugliness:</p>
<p><code>b=$(echo "$QUERY_STRING" | sed -n 's/^.*b=\([^&]*\).*$/\1/p' | sed "s/%20/ /g")</code></p>
<p>which will set $b to whatever was found in $QUERY_STRING for <code>b</code>. However, my script has grown to have over ten input parameters. Is there an easier way to automatically convert the parameters in $QUERY_STRING into environment variables usable by bash?</p>
<p>Maybe I'll just use a for loop of some sort, but it'd be even better if the script was smart enough to automatically detect each parameter and maybe build an array that looks something like this:</p>
<pre><code>${parm[a]}=123
${parm[b]}=456
${parm[c]}=ok
</code></pre>
<p>How could I write code to do that?</p> | 3,919,908 | 16 | 3 | null | 2010-10-12 23:11:57.187 UTC | 8 | 2021-11-04 09:19:03.803 UTC | 2019-09-28 15:56:31.013 UTC | null | 1,783,163 | null | 125,380 | null | 1 | 27 | bash|cgi | 53,916 | <p>Try this:</p>
<pre><code>saveIFS=$IFS
IFS='=&'
parm=($QUERY_STRING)
IFS=$saveIFS
</code></pre>
<p>Now you have this:</p>
<pre><code>parm[0]=a
parm[1]=123
parm[2]=b
parm[3]=456
parm[4]=c
parm[5]=ok
</code></pre>
<p>In Bash 4, which has associative arrays, you can do this (using the array created above):</p>
<pre><code>declare -A array
for ((i=0; i<${#parm[@]}; i+=2))
do
array[${parm[i]}]=${parm[i+1]}
done
</code></pre>
<p>which will give you this:</p>
<pre><code>array[a]=123
array[b]=456
array[c]=ok
</code></pre>
<p><strong>Edit:</strong></p>
<p>To use indirection in Bash 2 and later (using the <code>parm</code> array created above): </p>
<pre><code>for ((i=0; i<${#parm[@]}; i+=2))
do
declare var_${parm[i]}=${parm[i+1]}
done
</code></pre>
<p>Then you will have:</p>
<pre><code>var_a=123
var_b=456
var_c=ok
</code></pre>
<p>You can access these directly:</p>
<pre><code>echo $var_a
</code></pre>
<p>or indirectly:</p>
<pre><code>for p in a b c
do
name="var$p"
echo ${!name}
done
</code></pre>
<p>If possible, it's better to <a href="http://mywiki.wooledge.org/BashFAQ/006" rel="noreferrer">avoid indirection</a> since it can make code messy and be a source of bugs.</p> |
7,966,439 | How to unit test abstract classes | <p>Used the create unit tests tool in Visual Studio and obviously it tries to instantiate my abstract classes.</p>
<p>My question is: Should I try to unit test the way Visual Studio is trying to get me to do it, or should I create a mock class to be instantiated, or should I only test the methods that use this abstract class?</p>
<p>Thanks.</p> | 7,966,533 | 5 | 0 | null | 2011-11-01 12:28:32.287 UTC | null | 2021-04-22 10:46:22.673 UTC | null | null | null | null | 849,843 | null | 1 | 43 | c#|visual-studio|unit-testing | 38,339 | <p>If there are methods on this abstract class that are worth testing, then you should test them. You could always subclass the abstract class for the test (and name it like MyAbstractClassTesting) and test this new concrete class.</p> |
8,305,259 | Check if date is in the past Javascript | <p>All,
I'm using the jQuery UI for the date picker. I'm trying to check with javascript though that the date the user has entered is in the past. Here is my form code:</p>
<pre><code><input type="text" id="datepicker" name="event_date" class="datepicker">
</code></pre>
<p>Then how would I check this with Javascript to make sure it isn't a date in the past? Thanks</p> | 8,305,306 | 6 | 0 | null | 2011-11-29 02:56:41.44 UTC | 14 | 2022-09-20 14:40:02.057 UTC | 2011-11-29 03:01:54.473 UTC | null | 479,863 | null | 1,048,676 | null | 1 | 71 | javascript|jquery|jquery-ui|validation|date | 138,278 | <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('#datepicker').datepicker().change(evt => {
var selectedDate = $('#datepicker').datepicker('getDate');
var now = new Date();
now.setHours(0,0,0,0);
if (selectedDate < now) {
console.log("Selected date is in the past");
} else {
console.log("Selected date is NOT in the past");
}
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<input type="text" id="datepicker" name="event_date" class="datepicker"></code></pre>
</div>
</div>
</p> |
7,814,928 | How to load a xib file in a UIView | <p>I have been searching everywhere and nothing so far has worked for me.</p>
<p>Basically I want to have a .xib file called rootView.xib and inside it I want to have a UIView (lets call it containerView) that takes up only half of the screen (so there would be the regular view and a new view). Then I want a different .xib file called firstView.xib and load it inside of containerView. So I can have a bunch of stuff on firstView.xib and a bunch of different stuff in rootView.xib and load my firstView.xib inside of containerView in rootView.xib but since it only takes up half of the screen you would still see the stuff on rootView.xib</p> | 7,814,977 | 7 | 1 | null | 2011-10-18 23:24:26.783 UTC | 31 | 2019-03-07 14:04:54.83 UTC | 2016-05-26 06:58:31.433 UTC | null | 1,974,224 | null | 889,439 | null | 1 | 112 | ios|objective-c|uiview|xib | 163,608 | <p>To get an object from a xib file programatically you can use: <code>[[NSBundle mainBundle] loadNibNamed:@"MyXibName" owner:self options:nil]</code> which returns an array of the top level objects in the xib.</p>
<p>So, you <em>could</em> do something like this:</p>
<pre><code>UIView *rootView = [[[NSBundle mainBundle] loadNibNamed:@"MyRootView" owner:self options:nil] objectAtIndex:0];
UIView *containerView = [[[NSBundle mainBundle] loadNibNamed:@"MyContainerView" owner:self options:nil] lastObject];
[rootView addSubview:containerView];
[self.view addSubview:rootView];
</code></pre> |
4,546,131 | Using unique constraint on Hibernate JPA2 | <p>How can I implement my unique constraints on the hibernate POJO's? assuming the database doesn't contain any. </p>
<p>I have seen the unique attribute in <code>@Column()</code> annotation but I couldn't get it to work?<br>
What if I want to apply this constraint to more than one column?</p> | 4,546,504 | 3 | 1 | null | 2010-12-28 12:44:42.69 UTC | 3 | 2016-04-21 09:44:09.21 UTC | 2016-04-21 09:44:09.21 UTC | null | 1,413,133 | null | 364,746 | null | 1 | 24 | java|hibernate|unique|unique-constraint | 59,235 | <p>Bascially, you cannot implement unique constraint without database support. </p>
<p><code>@UniqueConstraint</code> and <code>unique</code> attribute of <code>@Column</code> are instructions for schema generation tool to generate the corresponsing constraints, they don't implement constraints itself.</p>
<p>You can do some kind of manual checking before inserting new entities, but in this case you should be aware of possible problems with concurrent transactions. </p>
<p>Therefore applying constraints in the database is the preferred choice.</p> |
4,065,606 | generate annotated doctrine2 entites from db schema | <p>Is it possible to generate Doctrine 2 entities, with the relevant docblock annotations, from an existing database schema?</p> | 5,347,979 | 4 | 1 | null | 2010-10-31 22:59:36.15 UTC | 11 | 2012-08-31 22:48:46.847 UTC | 2012-08-31 22:48:46.847 UTC | null | 759,866 | null | 436,441 | null | 1 | 6 | annotations|doctrine-orm|schema|docblocks | 9,274 | <p>I had to made these changes for the above code to work.. </p>
<pre><code><?php
use Doctrine\ORM\Tools\EntityGenerator;
ini_set("display_errors", "On");
$libPath = __DIR__; // Set this to where you have doctrine2 installed
// autoloaders
require_once $libPath . '/Doctrine/Common/ClassLoader.php';
$classLoader = new \Doctrine\Common\ClassLoader('Doctrine', $libPath);
$classLoader->register();
$classLoader = new \Doctrine\Common\ClassLoader('Entities', __DIR__);
$classLoader->register();
$classLoader = new \Doctrine\Common\ClassLoader('Proxies', __DIR__);
$classLoader->register();
// config
$config = new \Doctrine\ORM\Configuration();
$config->setMetadataDriverImpl($config->newDefaultAnnotationDriver(__DIR__ . '/Entities'));
$config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache);
$config->setProxyDir(__DIR__ . '/Proxies');
$config->setProxyNamespace('Proxies');
$connectionParams = array(
'path' => 'test.sqlite3',
'driver' => 'pdo_sqlite',
);
$em = \Doctrine\ORM\EntityManager::create($connectionParams, $config);
// custom datatypes (not mapped for reverse engineering)
$em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('set', 'string');
$em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
// fetch metadata
$driver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver(
$em->getConnection()->getSchemaManager()
);
$em->getConfiguration()->setMetadataDriverImpl($driver);
$cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory($em);
$cmf->setEntityManager($em);
$classes = $driver->getAllClassNames();
$metadata = $cmf->getAllMetadata();
$generator = new EntityGenerator();
$generator->setUpdateEntityIfExists(true);
$generator->setGenerateStubMethods(true);
$generator->setGenerateAnnotations(true);
$generator->generate($metadata, __DIR__ . '/Entities');
print 'Done!';
?>
</code></pre>
<p>and mysql connection configuration like : </p>
<pre><code>$connectionParams = array(
'driver' => 'pdo_mysql',
'host' => 'localhost',
'port' => '3306',
'user' => 'root',
'password' => 'root',
'dbname' => 'database',
'charset' => 'utf8',
);
</code></pre> |
4,058,979 | Find a point, a given distance, along a simple cubic bezier curve. (On an iPhone!) | <p>Imagine you have a completely normal four-point bezier curve (two points and two control points) created using curveToPoint:controlPoint1:controlPoint2: in your cocoa application:</p>
<p><img src="https://i.stack.imgur.com/NyU4W.gif" alt="simple cubic bezier curve example">
<br>
How do you find points (and the tangents), along the curve?</p>
<hr>
<p>Later: for a <strong>complete, simplified, solution</strong> based on Michal's answer below, click to:<br>
<a href="https://stackoverflow.com/questions/4089443">Find the tangent of a point on a cubic bezier curve (on an iPhone)</a></p>
<p>And just copy and paste the code from: <a href="https://stackoverflow.com/a/31317254/294884">https://stackoverflow.com/a/31317254/294884</a></p> | 4,060,392 | 4 | 0 | null | 2010-10-30 13:53:21.653 UTC | 14 | 2021-01-07 09:18:08.953 UTC | 2017-05-23 12:31:57.777 UTC | null | -1 | null | 294,884 | null | 1 | 16 | iphone|ipad|bezier | 12,378 | <p>There's some simple math behind calculating the positions, you can read about it in every paper discussing Bézier curves, even on wikipedia. Anyway, I can relate to everybody who's in trouble to actually implement it in code, so I wrote this sample UIView as it's probably the easiest way to get you started.</p>
<pre><code>#import "MBBezierView.h"
CGFloat bezierInterpolation(CGFloat t, CGFloat a, CGFloat b, CGFloat c, CGFloat d) {
CGFloat t2 = t * t;
CGFloat t3 = t2 * t;
return a + (-a * 3 + t * (3 * a - a * t)) * t
+ (3 * b + t * (-6 * b + b * 3 * t)) * t
+ (c * 3 - c * 3 * t) * t2
+ d * t3;
}
@implementation MBBezierView
- (void)drawRect:(CGRect)rect {
CGPoint p1, p2, p3, p4;
p1 = CGPointMake(30, rect.size.height * 0.33);
p2 = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
p3 = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));
p4 = CGPointMake(-30 + CGRectGetMaxX(rect), rect.size.height * 0.66);
[[UIColor blackColor] set];
[[UIBezierPath bezierPathWithRect:rect] fill];
[[UIColor redColor] setStroke];
UIBezierPath *bezierPath = [[[UIBezierPath alloc] init] autorelease];
[bezierPath moveToPoint:p1];
[bezierPath addCurveToPoint:p4 controlPoint1:p2 controlPoint2:p3];
[bezierPath stroke];
[[UIColor brownColor] setStroke];
for (CGFloat t = 0.0; t <= 1.00001; t += 0.05) {
CGPoint point = CGPointMake(bezierInterpolation(t, p1.x, p2.x, p3.x, p4.x), bezierInterpolation(t, p1.y, p2.y, p3.y, p4.y));
UIBezierPath *pointPath = [UIBezierPath bezierPathWithArcCenter:point radius:5 startAngle:0 endAngle:2*M_PI clockwise:YES];
[pointPath stroke];
}
}
@end
</code></pre>
<p>This is what I get:</p>
<p><img src="https://i.stack.imgur.com/d1Tyr.png" alt="alt text"></p> |
4,154,707 | Delete from one table with join | <p>I'm trying to delete records from one database based on a selection criteria of another. We have two tables, emailNotification which stores a list of jobs and emails. Then we have jobs. I want to clear out emailNotifications for jobs that have been closed. I found some earlier examples on Stackoverflow that lead me to this type of syntax (I was previously trying to do the join before the where). </p>
<pre><code>DELETE FROM emailNotification
WHERE notificationId IN (
SELECT notificationId FROM emailNotification e
LEFT JOIN jobs j ON j.jobId = e.jobId
WHERE j.active = 1
)
</code></pre>
<p>I'm getting the error, you can't specify the target table 'emailNotication' for update in the FROM Clause.</p> | 4,154,876 | 4 | 1 | null | 2010-11-11 13:10:22.68 UTC | 7 | 2018-10-21 10:14:55.123 UTC | 2015-07-11 19:17:01.097 UTC | null | 4,370,109 | null | 158,244 | null | 1 | 46 | mysql|left-join|sql-delete | 61,945 | <p>I am not sure about your requirement.
What I understood from your question is you want to delete all the emails of jobs which are closed.
try this one;</p>
<pre><code>DELETE e FROM emailNotification e
LEFT JOIN jobs j ON j.jobId = e.jobId
WHERE j.active = 1 AND CURDATE() < j.closeDate
</code></pre> |
4,059,163 | CSS Language Speak: Container vs Wrapper? | <p>What's the difference between container and wrapper? And what is meant by each?</p> | 4,059,171 | 4 | 1 | null | 2010-10-30 14:40:16.767 UTC | 27 | 2022-09-21 15:52:22.817 UTC | 2010-10-30 14:45:38.133 UTC | null | 106,224 | null | 251,257 | null | 1 | 61 | html|css | 45,926 | <p>There is no difference between them. </p>
<p>It's just what you like to call the <code><div></code> that, often, contains all content of a page</p> |
4,088,532 | Custom ORDER BY Explanation | <p>I found this some time ago and have been using it since; however, looking at it today, I realized that I do not fully understand why it works. Can someone shed some light on it for me?</p>
<pre><code>ORDER BY s.type!= 'Nails',
s.type!= 'Bolts',
s.type!= 'Washers',
s.type!= 'Screws',
s.type!= 'Staples',
s.type!= 'Nuts', ...
</code></pre>
<p>If I order by s.type, it orders alphabetically. If I use the example above it uses the same order as the line positions. What I don't understand is the use of !=. If I use = it appears in the opposite order. I cannot wrap my head around the concept of this.</p>
<p>It would reason to me that using = in place of the !='s above would place Nails first in position, but it does not, it place it in the last. I guess my question is this: Why do i have to use !=, not = in this situation?</p> | 4,088,794 | 4 | 2 | null | 2010-11-03 15:12:10.897 UTC | 24 | 2017-09-12 09:11:23.433 UTC | null | null | null | null | 469,437 | null | 1 | 73 | postgresql|sql-order-by | 30,039 | <p>I've never seen it but it seems to make sense.</p>
<p>At first it orders by <code>s.type != 'Nails'</code>. This is <code>false</code> for every row that contains <code>Nails</code> in the <code>type</code> column. After that it is sorted by <code>Bolts</code>. Again for all columns that do contain <code>Bolts</code> as a <code>type</code> this evaluates to false. And so on.</p>
<p>A small test reveals that <code>false</code> is ordered before <code>true</code>. So you have the following: First you get all rows with <code>Nails</code> on top because the according <code>ORDER BY</code> evaluated to <code>false</code> and <code>false</code> comes first. The remaining rows are sorted by the second <code>ORDER BY</code> criterion. And so on.</p>
<pre>
type | != Nails | != Bolts | != Washers
'Nails' | false | true | true
'Bolts' | true | false | true
'Washers' | true | true | false
</pre> |
4,139,379 | http keep-alive in the modern age | <p>So according to the haproxy author, who knows a thing or two about http: </p>
<blockquote>
<p>Keep-alive was invented to reduce CPU
usage on servers when CPUs were 100
times slower. But what is not said is
that persistent connections consume a
lot of memory while not being usable
by anybody except the client who
openned them. Today in 2009, CPUs are
very cheap and memory is still limited
to a few gigabytes by the architecture
or the price. If a site needs
keep-alive, there is a real problem.
Highly loaded sites often disable
keep-alive to support the maximum
number of simultaneous clients. The
real downside of not having keep-alive
is a slightly increased latency to
fetch objects. Browsers double the
number of concurrent connections on
non-keepalive sites to compensate for
this.</p>
</blockquote>
<p>(from <a href="http://haproxy.1wt.eu/" rel="noreferrer">http://haproxy.1wt.eu/</a>)</p>
<p>Is this in line with other peoples experience? ie without keep-alive - is the result barely noticable now? (its probably worth noting that with websockets etc - a connection is kept "open" regardless of keep-alive status anyway - for very responsive apps).
Is the effect greater for people who are remote from the server - or if there are many artifacts to load from the same host when loading a page? (I would think things like CSS, images and JS are increasingly coming from cache friendly CDNs). </p>
<p>Thoughts? </p>
<p>(not sure if this is a serverfault.com thing, but I won't cross post until someone tells me to move it there). </p> | 4,141,920 | 4 | 4 | null | 2010-11-09 22:32:57.27 UTC | 68 | 2015-11-03 23:45:06.59 UTC | 2012-07-20 10:47:09.503 UTC | null | 213,269 | null | 699 | null | 1 | 98 | http|webserver|keep-alive|haproxy | 27,190 | <p>Hey since I'm the author of this citation, I'll respond :-)</p>
<p>There are two big issues on large sites : concurrent connections and latency. Concurrent connection are caused by slow clients which take ages to download contents, and by idle connection states. Those idle connection states are caused by connection reuse to fetch multiple objects, known as keep-alive, which is further increased by latency. When the client is very close to the server, it can make an intensive use of the connection and ensure it is almost never idle. However when the sequence ends, nobody cares to quickly close the channel and the connection remains open and unused for a long time. That's the reason why many people suggest using a very low keep-alive timeout. On some servers like Apache, the lowest timeout you can set is one second, and it is often far too much to sustain high loads : if you have 20000 clients in front of you and they fetch on average one object every second, you'll have those 20000 connections permanently established. 20000 concurrent connections on a general purpose server like Apache is huge, will require between 32 and 64 GB of RAM depending on what modules are loaded, and you can probably not hope to go much higher even by adding RAM. In practice, for 20000 clients you may even see 40000 to 60000 concurrent connections on the server because browsers will try to set up 2 to 3 connections if they have many objects to fetch.</p>
<p>If you close the connection after each object, the number of concurrent connections will dramatically drop. Indeed, it will drop by a factor corresponding to the average time to download an object by the time between objects. If you need 50 ms to download an object (a miniature photo, a button, etc...), and you download on average 1 object per second as above, then you'll only have 0.05 connection per client, which is only 1000 concurrent connections for 20000 clients.</p>
<p>Now the time to establish new connections is going to count. Far remote clients will experience an unpleasant latency. In the past, browsers used to use large amounts of concurrent connections when keep-alive was disabled. I remember figures of 4 on MSIE and 8 on Netscape. This would really have divided the average per-object latency by that much. Now that keep-alive is present everywhere, we're not seeing that high numbers anymore, because doing so further increases the load on remote servers, and browsers take care of protecting the Internet's infrastructure.</p>
<p>This means that with todays browsers, it's harder to get the non-keep-alive services as much responsive as the keep-alive ones. Also, some browsers (eg: Opera) use heuristics to try to use pipelinining. Pipelining is an efficient way of using keep-alive, because it almost eliminates latency by sending multiple requests without waiting for a response. I have tried it on a page with 100 small photos, and the first access is about twice as fast as without keep-alive, but the next access is about 8 times as fast, because the responses are so small that only latency counts (only "304" responses).</p>
<p>I'd say that ideally we should have some tunables in the browsers to make them keep the connections alive between fetched objects, and immediately drop it when the page is complete. But we're not seeing that unfortunately.</p>
<p>For this reason, some sites which need to install general purpose servers such as Apache on the front side and which have to support large amounts of clients generally have to disable keep-alive. And to force browsers to increase the number of connections, they use multiple domain names so that downloads can be parallelized. It's particularly problematic on sites making intensive use of SSL because the connection setup is even higher as there is one additional round trip.</p>
<p>What is more commonly observed nowadays is that such sites prefer to install light frontends such as haproxy or nginx, which have no problem handling tens to hundreds of thousands of concurrent connections, they enable keep-alive on the client side, and disable it on the Apache side. On this side, the cost of establishing a connection is almost null in terms of CPU, and not noticeable at all in terms of time. That way this provides the best of both worlds : low latency due to keep-alive with very low timeouts on the client side, and low number of connections on the server side. Everyone is happy :-)</p>
<p>Some commercial products further improve this by reusing connections between the front load balancer and the server and multiplexing all client connections over them. When the servers are close to the LB, the gain is not much higher than previous solution, but it will often require adaptations on the application to ensure there is no risk of session crossing between users due to the unexpected sharing of a connection between multiple users. In theory this should never happen. Reality is much different :-)</p> |
4,059,624 | Can I use params in Action or Func delegates? | <p>When I'm trying to use params in an Action delegate...</p>
<pre><code>private Action<string, params object[]> WriteToLogCallBack;
</code></pre>
<p>I received this design time error:</p>
<blockquote>
<p>Invalid token 'params' in class, struct, or interface member declaration</p>
</blockquote>
<p>Any help!</p> | 4,059,664 | 5 | 1 | null | 2010-10-30 16:36:36.223 UTC | 6 | 2022-09-07 22:30:49.367 UTC | 2010-10-30 16:52:03.75 UTC | null | 322,355 | null | 322,355 | null | 1 | 51 | c#|delegates|action|params-keyword | 33,368 | <p>How about this workaround?</p>
<pre><code>private Action<string, object[]> writeToLogCallBack;
public void WriteToLogCallBack(string s, params object[] args)
{
if(writeToLogCallBack!=null)
writeToLogCallBack(s,args);
}
</code></pre>
<p>Or you could define your own delegate type:</p>
<pre><code>delegate void LogAction(string s, params object[] args);
</code></pre> |
4,351,370 | How can I determine what flash player version a swf was published for? | <p>I have a SWF of unknown origin, and I need to know which flash player version it was targeted at when it was published. How do I get this info?</p> | 4,351,747 | 6 | 0 | null | 2010-12-04 01:20:04.443 UTC | 8 | 2014-04-11 15:19:49.88 UTC | 2013-06-22 20:05:27.44 UTC | null | 336,781 | null | 336,781 | null | 1 | 35 | actionscript-3|flash | 24,308 | <p>The 4th byte in the SWF file carries the version number, for example 0A is for Flash Player 10.</p>
<p>EDIT: Because of the high interest this question got I've decided to give more feedback</p>
<p>The first 8 bytes of any SWF file are not compressed, the rest of the file could be compressed (or not) by zlib compression.</p>
<ul>
<li>1st byte: 'F' (not compressed) OR 'C' (compressed).</li>
<li>2nd byte: 'W' always.</li>
<li>3rd byte: 'S' always.</li>
<li>4th byte: version number (09 means this file is targeted at Flash Player 9 and so on...)</li>
<li>5th to 8th: Length of entire file in bytes.</li>
</ul> |
4,529,640 | Get the year from specified date php | <p>I have a date in this format <code>2068-06-15</code>. I want to get the year from the date, using php functions. Could someone please suggest how this could be done.</p> | 4,529,680 | 10 | 1 | null | 2010-12-25 07:44:46.807 UTC | 10 | 2022-03-11 06:36:11.707 UTC | 2012-04-30 15:42:34.367 UTC | null | 1,268,895 | null | 472,375 | null | 1 | 82 | php|date | 177,411 | <pre><code>$date = DateTime::createFromFormat("Y-m-d", "2068-06-15");
echo $date->format("Y");
</code></pre>
<p>The DateTime class does not use an unix timestamp internally, so it han handle dates before 1970 or after 2038.</p> |
14,579,792 | Android Activity Transition in a ListView | <p>I'm trying to accomplish the following Activity transition in Android:</p>
<p><img src="https://i.stack.imgur.com/0gPQd.png" alt="enter image description here"></p>
<p>In <strong>1</strong> we see an usual ListView. Now (<strong>2</strong>), when I place my finger on a ListView element and slide my finger to the left, all the other ListView elements move away, except the one which has my finger on it. If the transition if completed, the "selected" ListView element expands over the screen and shows some content.</p>
<p><strong>Question</strong>: Is this transition possible with stock API functions?</p> | 14,715,632 | 5 | 5 | null | 2013-01-29 09:41:22.873 UTC | 14 | 2015-04-23 23:44:24.77 UTC | null | null | null | null | 1,188,357 | null | 1 | 11 | java|android|listview|animation|transition | 5,292 | <p>While @hasanghaforian is techincally correct, subclassing AdapterView is extremely difficult. I suggest you go with this approach. I've included a full working example. </p>
<ol>
<li>Put your ListView view in a relativeLayout</li>
<li>OnClick, inflate a copy of your renderer</li>
<li>Find the global coordinates for where the renderer sits in relationship to the parent of the ListView</li>
<li>Add the copied renderer to the RelativeLayout (parent of ListView)</li>
<li>Animate the listView away</li>
<li>On the end of that animate, animate your new renderer</li>
<li>Profit!</li>
</ol>
<pre><code>public class MainActivity extends Activity {
private RelativeLayout layout;
private ListView listView;
private MyRenderer selectedRenderer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
layout = new RelativeLayout(this);
setContentView(layout);
listView = new ListView(this);
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
layout.addView(listView, rlp);
listView.setAdapter(new MyAdapter());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// find out where the clicked view sits in relationship to the
// parent container
int t = view.getTop() + listView.getTop();
int l = view.getLeft() + listView.getLeft();
// create a copy of the listview and add it to the parent
// container
// at the same location it was in the listview
selectedRenderer = new MyRenderer(view.getContext());
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(view.getWidth(), view
.getHeight());
rlp.topMargin = t;
rlp.leftMargin = l;
selectedRenderer.textView.setText(((MyRenderer) view).textView.getText());
layout.addView(selectedRenderer, rlp);
view.setVisibility(View.INVISIBLE);
// animate out the listView
Animation outAni = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f,
Animation.RELATIVE_TO_SELF, -1f, Animation.RELATIVE_TO_SELF, 0f,
Animation.RELATIVE_TO_SELF, 0f);
outAni.setDuration(1000);
outAni.setFillAfter(true);
outAni.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
ScaleAnimation scaleAni = new ScaleAnimation(1f,
1f, 1f, 2f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
scaleAni.setDuration(400);
scaleAni.setFillAfter(true);
selectedRenderer.startAnimation(scaleAni);
}
});
listView.startAnimation(outAni);
}
});
}
public class MyAdapter extends BaseAdapter {
@Override
public int getCount() {
return 10;
}
@Override
public String getItem(int position) {
return "Hello World " + position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
MyRenderer renderer;
if (convertView != null)
renderer = (MyRenderer) convertView;
else
renderer = new MyRenderer(MainActivity.this);
renderer.textView.setText(getItem(position));
return renderer;
}
}
public class MyRenderer extends RelativeLayout {
public TextView textView;
public MyRenderer(Context context) {
super(context);
setPadding(20, 20, 20, 20);
setBackgroundColor(0xFFFF0000);
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
rlp.addRule(CENTER_IN_PARENT);
textView = new TextView(context);
addView(textView, rlp);
}
}
}
</code></pre> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.